Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@
.externalNativeBuild
.cxx
local.properties
.idea/
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ dependencyResolutionManagement {
mavenCentral()
}
}
rootProject.name = "BillCalculator"
rootProject.name = "Java-Module-Project"
91 changes: 91 additions & 0 deletions src/main/java/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import java.util.Scanner;
import java.lang.Math;
public class App {
Scanner sc = new Scanner(System.in);
Calculator calculator = new Calculator();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так как калькулятор один на всю программу, можно сделать его, его методы и поля static,чтобы не нужно было создавать его экземпляр. Тогда можно будет просто вызывать методы напрямую: Calculator:.getSum()


public void run() {
int peopleCount = getPeopleCount();
readItems();
double sum = calculator.getSum();
String info = calculator.getItemsAsStr();
System.out.println(info);
double avg = sum / peopleCount;
double roundedValue = Math.floor(avg);
String template;
if (roundedValue % 100 > 9 && roundedValue % 100 < 21){
template = "%.2f рублей";
}
else if (roundedValue % 10 == 1) {
template = "%.2f рубль";
}
else if ( roundedValue % 10 > 1 && roundedValue % 10 < 5 ) {
template = "%.2f рубля";
}
else {
template = "%.2f рублей";
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для множественных вариантов лучше использовать конструкцию switch

System.out.println(String.format(template, avg));


}
private int getPeopleCount(){
while(true){
try {
System.out.println("Укажите колличество человек");
String myString = sc.next();
int peopleCount = Integer.parseInt(myString);
if (peopleCount <= 1) {
System.out.println("Колличество человек должно быть больше 1");
continue;
}
else {
return peopleCount;
}
} catch (NumberFormatException e) {
System.out.println("Неревный ввод");

}

}
}
private void readItems(){
while (true) {
System.out.println("Введите название продукта");
String title = sc.next();
while (true) {
try {
System.out.println("Введите цену продукта");
String myString1 = sc.next();
double price = Double.parseDouble(myString1);
if (price > 0) {
Item item = new Item(title, price);
calculator.addItem(item);
System.out.println("Товар успешно добавлен");
System.out.println("Если это все продукты, то введите 'exit', иначе введите любой символ");
String finish = sc.next();
if (finish.equalsIgnoreCase("exit")) {
break;
} else {
continue;
}
} else {
System.out.println("Неревный ввод");
continue;
}
} catch (NumberFormatException e) {
System.out.println("Неревный ввод");

}


}
break;



}
}


}
38 changes: 19 additions & 19 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
class Calculator {

int friendsCount;

String cart = "Добавленные товары:";
double totalPrice = 0;

Calculator(int friendsCount) {
this.friendsCount = friendsCount;
import java.util.ArrayList;
public class Calculator{
ArrayList<Item> items = new ArrayList<Item>();
public double getSum(){
double sum = 0;
for (Item item: items){
sum += item.price;
}
return sum;
}

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;

System.out.println(item.name + " в корзине");
public void addItem(Item item){
items.add(item);
}

double divideSum() {
return totalPrice / friendsCount;
public String getItemsAsStr(){
String info = "Добавленные товары: \n";
for (Item item: items){
info += item.toString() + "\n";
}
return info;
}
}

}
17 changes: 0 additions & 17 deletions src/main/java/Formatter.java

This file was deleted.

16 changes: 9 additions & 7 deletions src/main/java/Item.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
class Item {

String name;
public class Item {
String title;
double price;

Item(String name, double price) {
this.name = name;
this.price = price;
Item(String Title, double Price) {
title = Title;
price = Price;
}
public String toString(){
String priceAsStr = Double.toString(price);
return title + " " + priceAsStr;
}
}
47 changes: 3 additions & 44 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,49 +1,8 @@
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int friendCount;
while (true) {
System.out.println("На сколько человек необходимо разделить счет?");
friendCount = scanner.nextInt();

if (friendCount > 1) {
break;
} else if (friendCount == 1) {
System.out.println(
"Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы.");
} else {
System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз.");
}
}

Calculator calculator = new Calculator(friendCount);

while (true) {
System.out.println("Введите название товара");
String name = scanner.next();

System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]");
double price = scanner.nextDouble();

calculator.addItem(new Item(name, price));

System.out.println(
"Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления");
String answer = scanner.next();

if (answer.equalsIgnoreCase("Завершить")) {
break;
}
}

double result = calculator.divideSum();
Formatter formatter = new Formatter();

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
App app = new App();
app.run();
}
}