Skip to content
Closed
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
21 changes: 21 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class Calculator {
double totalAmount = 0;
String listOfProducts = "";

void AddProductToCalculator(String productName, double costOfGood){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Тут тоже лучше с маленькой буквы


FillInTheListOfProducts(productName);
sum(costOfGood);

System.out.println("Товар добавлен - " + productName);
}

void sum(double sum) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Можно сделать приватным, так как используется только в рамках данного класса.

this.totalAmount = this.totalAmount + sum;
}

void FillInTheListOfProducts(String productName) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Тоже можно сделать приватным, а также лучше переименовать метод, чтобы начиналось с маленькой буквы

this.listOfProducts = this.listOfProducts + "\n" + productName;
}

}
103 changes: 100 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,105 @@
import java.util.Scanner;

public class Main {

// private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");

Scanner sc = new Scanner(System.in);

int numberOfPeople;
double costOfGoods;

// 1. Вводим количество посетителей.

System.out.println("На скольких человек разделить счет?");

while (true) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Лучше не писать код одним полотном, а разделять на смысловые кусочки, которые можно вынести в функцию. Например, этот цикл можно вынести в функцию и назвать в стиле readNumberOfPeople. Так код будет выглядить аккуратнее, его будет легче читать и другим разработчиком будет легче понимать общую структуру.


while (!sc.hasNextInt()) {
System.out.println("Некорректный ввод, введите целое число.");
sc.next();
}
numberOfPeople = sc.nextInt();

if (numberOfPeople <=1) {
System.out.println("Количество посетителей должно быть больше 1.");
} else {
System.out.println("Количество посетителей - " + numberOfPeople);
break;
}

}

Calculator calc = new Calculator();

// 2.1 Вводим название товара

while (true) {

System.out.println("Введите название товара");

String productName = sc.next();

if (productName.equalsIgnoreCase("ЗАВЕРШИТЬ")){

// 3.1 Выводим список товаров
System.out.println(calc.listOfProducts);

// 3.2 Выводим цену для одного человека
double costPerPerson = calc.totalAmount / (double) numberOfPeople;

System.out.println(String.format("%.2f",costPerPerson) + " " + GetCurrency(costPerPerson));

break;

} else {

while (true) {

// 2.2 Вводим стоимость товара
System.out.println("Введите стоимость товара");

while (!sc.hasNextDouble()) {
System.out.println("Некорректный ввод, введите число.");
sc.next();
}
costOfGoods = sc.nextDouble();



if (costOfGoods > 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Так как мы даем пользователю возможность вводить дробное число, возникает ситуация, когда над приложением захотят поиздеваться и ввести какую-нибудь нереальную сумму (например, 0,00000000009). В такой ситуации при округление получится, что все должны заплатить по 0 рублей и кто-то потеряет в деньгих. Можно было бы попробовать добавить валидацию таких ситуаций или сразу ограничить ввод 2 знаками после запятой и уведомить об этом пользователя. А может быть ограничить минимальную цену, которую можно указать.

calc.AddProductToCalculator(productName,costOfGoods);
break;
} else {
System.out.println("Введите не нулевую стоимость товара." + numberOfPeople);
}

}

}

} //while (true)

}

public static String GetCurrency(double costPerPerson){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Имена методов принято начинать с маленькой буквы


String currency = "рублей";

int integerPartOfNumber = (int)costPerPerson;

String strIntegerPartOfNumber = Integer.toString(integerPartOfNumber);

String theLastDigit = strIntegerPartOfNumber.substring(strIntegerPartOfNumber.length() - 1);

if (theLastDigit.equals("1")){

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⏫ Тут делается не правильное склонение для числе 11-14. Это специфичный кейс и его стоит обработать отдельно.

currency = "рубль";
} else if (theLastDigit.equals("2") || theLastDigit.equals("3") || theLastDigit.equals("4")) {
currency = "рубля";
}

return currency;
}
}