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
28 changes: 28 additions & 0 deletions src/main/java/CalculatorBill.java
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

image
После выполнения этого ифа программа пойдет дальше и поэтому будет два раза выведена строка) Для того, чтобы программа вышла из метода, нужно написать return. В твоем случае это внутри ифа)

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 + ".");
}
}
30 changes: 28 additions & 2 deletions src/main/java/Main.java
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());
}
}
}
}

}

53 changes: 53 additions & 0 deletions src/main/java/ProductAndPrice.java
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

image

Где-то здесь есть интересный баг. Если сначала ввести некорректное число (например, отрицательное), а дальше ввести не число (слово), то приложение ловит ошибку InputMismatchException

image

Если провалить в метод nextDouble (нажать ctrl + click или cmd+click), то можно увидеть, что такое исключение выбрасывается, когда не может привестись к типу double. У тебя ошибка возникает из-за вложенного while, потому что если ввести некорректное число, мы в него попадем, а дальше уже можно вводить любые символы и из-за этого выбросится ошибка. Вариант исправления: Следует while (price <= 0) заменить на if (price <= 0), внутри которого написать ошибку и использовать continue, чтобы прервать текущую итерацию цикла while (true) и перейти к следующей сразу, без выполнения кода ниже

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();
}
}
}
}