Repository navigation
Практическая работа №1 #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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){ | ||
|
|
||
| FillInTheListOfProducts(productName); | ||
| sum(costOfGood); | ||
|
|
||
| System.out.println("Товар добавлен - " + productName); | ||
| } | ||
|
|
||
| void sum(double sum) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ⏫ Можно сделать приватным, так как используется только в рамках данного класса. |
||
| this.totalAmount = this.totalAmount + sum; | ||
| } | ||
|
|
||
| void FillInTheListOfProducts(String productName) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ⏫ Тоже можно сделать приватным, а также лучше переименовать метод, чтобы начиналось с маленькой буквы |
||
| this.listOfProducts = this.listOfProducts + "\n" + productName; | ||
| } | ||
|
|
||
| } | ||
| 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ⏫ Лучше не писать код одним полотном, а разделять на смысловые кусочки, которые можно вынести в функцию. Например, этот цикл можно вынести в функцию и назвать в стиле |
||
|
|
||
| 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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){ | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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")){ | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
⏫ Тут тоже лучше с маленькой буквы