-
Notifications
You must be signed in to change notification settings - Fork 0
First request on this 2nd sprint's project #1
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
base: main
Are you sure you want to change the base?
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,20 @@ | ||
| public class Calculator { | ||
|
|
||
| String listOfGoods = ""; | ||
| double totalPrice = 0; | ||
|
|
||
| public void formAListOfGoodsAndTheirPrice() { | ||
| while (true) { | ||
| Item item = new Item(); | ||
| String nameOfItem = item.addAnItem(); | ||
| double priceOfItem = item.addAnItemPrice(); | ||
| listOfGoods += nameOfItem + " " + String.format("%.2f", item.priceOfItem) + "\n"; | ||
| totalPrice += priceOfItem; | ||
| System.out.println("Товар успешно добавлен! Вы хотите добавить еще товар?"); | ||
| System.out.println("Введите команду \"Завершить\" для того, чтоб завершить процесс добавления товаров."); | ||
| String addOneMore = Main.sc.nextLine(); | ||
| if (addOneMore.equalsIgnoreCase("завершить")) break; | ||
| } | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| //Класс для проверки является ли введенный символ (символы) неотрицательным целым или вещественным числом. | ||
| public class IsItANumber { | ||
|
|
||
| public boolean naturalNum(String str) { | ||
|
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. В этой программе уже было использовано ключевое слово static, можно также сделать эти методы тоже static, так как они служебные. Тогда нам не нужно будет создавать экземпляр класса IsItANumber для вызова его методов |
||
| for (char c : str.toCharArray()) { | ||
| if (!Character.isDigit(c)) return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| public boolean doubleNum(String str) { | ||
| int nubmerOfDots = 0; | ||
| for (char c : str.toCharArray()) { | ||
| if (c == '.') nubmerOfDots += 1; | ||
| if (!(Character.isDigit(c) || c == '.') || nubmerOfDots > 1) return false; | ||
| } | ||
| return 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. Круто, что сам реализовал логику для проверки ввода, дело полезное. Также можно использовать готовые решения, например, методы Scanner.nextInt(), nextDouble() |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| public class Item { | ||
|
|
||
| String nameOfItem; | ||
| double priceOfItem; | ||
|
|
||
| public String addAnItem() { | ||
| System.out.println("Введите название товара."); | ||
| nameOfItem = Main.sc.nextLine(); | ||
| return nameOfItem; | ||
| } | ||
|
|
||
| public double addAnItemPrice() { | ||
| IsItANumber checkedString = new IsItANumber(); | ||
| System.out.println("Введите стоимость товара в формате \"рубли.копейки\"."); | ||
| while(true) { | ||
| String priceOfItem = Main.sc.nextLine(); | ||
| if (!(checkedString.doubleNum(priceOfItem))) { | ||
| System.out.println("Ошибка: \"Введен недопустимый символ или отрицательное число!\" Повторите ввод стоимости товара в виде числа!"); | ||
| } | ||
| else { | ||
| this.priceOfItem = Double.parseDouble(priceOfItem); | ||
| return this.priceOfItem; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,40 @@ | ||
| import java.util.Scanner; | ||
| public class Main { | ||
| public static Scanner sc = new Scanner(System.in); | ||
|
|
||
| public static void main(String[] args) { | ||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
| System.out.println("Привет Мир"); | ||
| //Первая часть задачи (ввод количества человек): | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
|
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. Лучше внести этот принтлн в метод correctedPersonsNumber, потому что это часть той логики |
||
| int personsNumber = correctedPersonsNumber(); | ||
|
|
||
| //Вторая часть задачи (формирование списка продуктов и подсчет их общей суммы): | ||
| Calculator calculator = new Calculator(); | ||
| calculator.formAListOfGoodsAndTheirPrice(); | ||
|
|
||
| //Третья часть задачи (вывод списка товаров и суммы, которую должен заплатить каждый человек): | ||
| System.out.println("Добавленные товары:\n" + calculator.listOfGoods); | ||
| System.out.printf("С каждого %.2f %s!%n", calculator.totalPrice / personsNumber, rubInCorrectCase(calculator.totalPrice / personsNumber)); | ||
| } | ||
|
|
||
| public static int correctedPersonsNumber() { | ||
|
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. В Java принята конвенция, согласно которой методы принято называть глаголами, см. https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html |
||
| IsItANumber checkedInput = new IsItANumber(); | ||
| while (true) { | ||
| String personsNumber = sc.nextLine(); | ||
| if (!checkedInput.naturalNum(personsNumber)) { | ||
| System.out.println("Ошибка: \"Введен недопустимый символ или отрицательное число!\" Повторите ввод!"); | ||
| } else if (Integer.parseInt(personsNumber) <= 1) { | ||
| System.out.println("Ошибка: \"Введенное количество человек меньше двух\"! Повторите ввод!"); | ||
| } else return Integer.parseInt(personsNumber); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public static String rubInCorrectCase(double sumOfEachPerson) { | ||
| int a = (int) sumOfEachPerson; | ||
|
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 rub; | ||
| if (a%10 == 1 && a%100 != 11) rub = "рубль"; | ||
| else if ((a%10 >= 2 && a%10 <= 4) && (a%100 != 12 && a%100 != 13 && a%100 != 14)) rub = "рубля"; | ||
| else rub = "рублей"; | ||
| return rub; | ||
| } | ||
|
|
||
| } | ||
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.
Такие подряд идущие println можно объединить в один.