Repository navigation
На проверку #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?
На проверку #1
Changes from all commits
19a3eb4
b96c3ab
0d0b479
d891a89
c399613
28e1e2d
9083aa9
852cfa1
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,28 @@ | ||
| class CalculatorBill { | ||
| public void calc(double totalPrice, int numberPeople) { | ||
| double payPerPerson = totalPrice / numberPeople; | ||
| double flooredpPp = Math.floor(payPerPerson); | ||
| String rub; | ||
| int lastDigit = (int) flooredpPp % 100; | ||
| if (11 <= lastDigit & lastDigit <= 19) { | ||
| rub = "рублей"; | ||
| System.out.println("Каждому нужно заплатить: " + String.format("%.2f", payPerPerson) + " " + rub + "."); | ||
| return; | ||
| } | ||
| int lastDigitTwo = (int) flooredpPp % 10; | ||
| switch (lastDigitTwo) { | ||
| case 1: | ||
| rub = "рубль"; | ||
| break; | ||
| case 2: | ||
| case 3: | ||
| case 4: | ||
| rub = "рубля"; | ||
| break; | ||
| default: | ||
| rub = "рублей"; | ||
| break; | ||
| } | ||
| System.out.println("Каждому нужно заплатить: " + String.format("%.2f", payPerPerson) + " " + rub + "."); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,32 @@ | ||
|
|
||
| import java.util.Scanner; | ||
|
|
||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| ProductAndPrice ProductAndPrice = new ProductAndPrice(); | ||
| CalculatorBill calculatorBill = new CalculatorBill(); | ||
|
|
||
| while (true) { | ||
| System.out.println("На сколько человек разделить счет?"); | ||
| String input = scanner.next(); | ||
|
|
||
| try { | ||
| int numberPeople = Integer.parseInt(input); | ||
|
|
||
| if (numberPeople > 1) { | ||
| ProductAndPrice.calculate(); | ||
| calculatorBill.calc(ProductAndPrice.totalPrice, numberPeople); | ||
| break; | ||
| } | ||
| System.out.println("Некорректное значение для подсчета."); | ||
| } catch (Exception exx) { | ||
| System.out.println("Преобразование к числу не получилось! Введите еще раз. " + exx.getMessage()); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| class ProductAndPrice { | ||
| public double totalPrice = 0.00; | ||
|
|
||
| public void calculate() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| String bill = ""; | ||
| String stop = "Завершить"; | ||
|
|
||
| while (true) { | ||
| System.out.println("Введите название товара:"); | ||
| String productName = scanner.next(); | ||
| System.out.println("Введите стоимость товара (стоимость должна быть в формате XX.XX (рубли.копейки)):"); | ||
| double price = getProductPrice(scanner); | ||
| bill = bill.concat(productName).concat("\n"); | ||
| System.out.println("Товар успешно добавлен в счет."); | ||
| totalPrice = totalPrice + price; | ||
| System.out.println("Хотите ли Вы добавить ещё один товар? Для того чтобы завершить процесс добавления товаров,напишите \"Завершить\"."); | ||
| String answer = scanner.next(); | ||
|
|
||
| if (answer.equalsIgnoreCase(stop)) { | ||
| System.out.println("Добавленные товары:" + "\n" + bill); | ||
| break; | ||
| } | ||
|
|
||
| } | ||
| } | ||
|
|
||
|
|
||
| double getProductPrice(Scanner scanner) { | ||
|
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. Где-то здесь есть интересный баг. Если сначала ввести некорректное число (например, отрицательное), а дальше ввести не число (слово), то приложение ловит ошибку InputMismatchException Если провалить в метод nextDouble (нажать ctrl + click или cmd+click), то можно увидеть, что такое исключение выбрасывается, когда не может привестись к типу double. У тебя ошибка возникает из-за вложенного while, потому что если ввести некорректное число, мы в него попадем, а дальше уже можно вводить любые символы и из-за этого выбросится ошибка. Вариант исправления: Следует |
||
| while (true) { | ||
| if (scanner.hasNextDouble()) { | ||
| double price = scanner.nextDouble(); | ||
| if (price <= 0) { | ||
| System.out.println("Стоимость должна быть >0. Введите стоимость товара еще раз."); | ||
| continue; | ||
| } | ||
| return price; | ||
| } else { | ||
| System.out.println("Преобразование к числу не получилось! Введите еще раз."); | ||
| scanner.next(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||


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.
После выполнения этого ифа программа пойдет дальше и поэтому будет два раза выведена строка) Для того, чтобы программа вышла из метода, нужно написать return. В твоем случае это внутри ифа)