Skip to content
Open
88 changes: 88 additions & 0 deletions src/main/java/Goods.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import java.util.Scanner;

public class Goods {
private double totalBill = 0;
private String goods = "";

/**
Метод создает String со списком товаров и их ценой, а также суммирует все товары
в отдельную переменную totalBill
*/
public void createListOfGoods() {
String tempGoods = "";
String userInputGoodName;
double userInputGoodValue;
Scanner scanner = new Scanner(System.in);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Думаю, что можно было создать один сканер в main и передавать его как аргумент в методы, в которых он необходим

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Некоторые методы я отметил private, которые используют Scanner, потому что они исполняют техническую работу внутри класса и не должны быть доступны вне класса. Поэтому из main не хотелось бы им передавать сканер...


while (true) {
if (tempGoods.isEmpty()) {
System.out.println("Введите название товара (Или \"Завершить\" для окончания формирования списка):");
} else {
System.out.println("Введите название следующего товара (Или \"Завершить\" для окончания формирования списка):");
}

userInputGoodName = scanner.nextLine();

if (userInputGoodName.equalsIgnoreCase("Завершить")) {
break;
}

if (tempGoods.isEmpty()) {
tempGoods = tempGoods.concat(userInputGoodName);
} else {
tempGoods = tempGoods.concat("\n" + userInputGoodName);
}

System.out.println("Введите стоимость товара в формате рубли.копейки (например 10.22):");

while (true) {
userInputGoodValue = checkUserInputAsDouble();
if (userInputGoodValue < 0) {
System.out.println("Стоимость товара должна быть неотрицательной");
} else {
break;
}
}

totalBill += userInputGoodValue;
tempGoods = tempGoods.concat(String.format(" - Цена: %.2f", userInputGoodValue));
}
goods = tempGoods;
}

/**
Метод проверяет, является ли ввод пользователя double
*/
private double checkUserInputAsDouble() {
Scanner scanner = new Scanner(System.in);
double correctDoubleInput;

while (true) {
try {
correctDoubleInput = Double.parseDouble(scanner.next());
break;
} catch (NumberFormatException e) {
System.out.println("Введите корректную стоимость в формате рубли.копейки (например 10.22):");
}
Comment on lines +61 to +66

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Отличный способ проверки на корректность ввода 👍

}


return correctDoubleInput;
}

/**
Метод выводит, сколько каждый человек должен заплатить в зависимости от
введенного количества гостей
*/
public void calculateAndShowResultsPerGuest(int numberOfGuests) {
if (goods.isEmpty()) {
System.out.println("Никаких товаров не было добавлено");
return;
}
System.out.println("Добавленные товары: \n" + goods);
double billPerPerson = totalBill / numberOfGuests;
String roubles = RoubleFormatter.returnRoubleString(billPerPerson);
System.out.println(String.format("Каждый человек должен заплатить %.2f %s", billPerPerson, roubles));
}

}
46 changes: 46 additions & 0 deletions src/main/java/Guests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.util.Scanner;

public class Guests {
private int numberOfGuests = 0;

/**
Метод устанавливает количество гостей, на которых необходимо разделить счет, на основе
ввода пользователя через консоль
*/
public void setNumberOfGuests() {
System.out.println("На скольких человек необходимо разделить счет?");
while (true) {
int tempNumberOfGuests = returnCorrectUserInputAsInt();
if (tempNumberOfGuests > 1) {
numberOfGuests = tempNumberOfGuests;
break;
} if (tempNumberOfGuests == 1) {
System.out.println("На одного счет делить смысла нет");
} if (tempNumberOfGuests < 1) {
System.out.println("Число должно быть больше 1");
}

}
}

/**
Метод проверяет, является ли ввод пользователя int
*/
private int returnCorrectUserInputAsInt() {
Scanner scanner = new Scanner(System.in);
int correctIntInput;
while (true) {
try {
correctIntInput = Integer.parseInt(scanner.next());
break;
} catch (NumberFormatException e) {
System.out.println("Введите корректное целое число гостей");
}
}
return correctIntInput;
}

public int getNumberOfGuests() {
return numberOfGuests;
}
}
10 changes: 9 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Guests firstGuestList = new Guests();
firstGuestList.setNumberOfGuests();

Goods testGoods = new Goods();


testGoods.createListOfGoods();
testGoods.calculateAndShowResultsPerGuest(firstGuestList.getNumberOfGuests());

}
}
15 changes: 15 additions & 0 deletions src/main/java/RoubleFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
public class RoubleFormatter {
public static String returnRoubleString(double sum) {
int integerValueOfSum = (int) sum;
if (integerValueOfSum % 100 > 10 && integerValueOfSum % 100 < 20) {
return "рублей";
}
if (integerValueOfSum % 10 == 1) {
return "рубль";
} else if (integerValueOfSum % 10 >= 2 && integerValueOfSum % 10 <= 4) {
return "рубля";
} else {
return "рублей";
}
}
}