Skip to content
Open
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
101 changes: 97 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,101 @@
public class Main {
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
Scanner scanner = new Scanner(System.in);

int guests = Calculator.getGuestsNumber(scanner);
String itemList = Calculator.getItemsList(scanner);
double costPerPerson = Calculator.getCostPerPerson(itemList, guests);

String rubleSuffix = Calculator.getRubleSuffix(costPerPerson);
System.out.println("Каждый гость должен заплатить " + String.format("%.2f", costPerPerson) + " " + rubleSuffix + ".");
}
}

class Calculator {

public static int getGuestsNumber(Scanner scanner) {
int guests = 0;
boolean guestsNum = false;
while (!guestsNum) {
System.out.print("Введите количество гостей: ");
if (scanner.hasNextInt()) {
guests = scanner.nextInt();
if (guests <= 1) {
System.out.println("Некорректное значение. Количество гостей должно быть больше 1.");
} else {
guestsNum = true;
}
} else {
System.out.println("Введите корректное число!");
scanner.next();
}
}
return guests;
}

public static String getItemsList(Scanner scanner) {
double totalValue = 0.0;
boolean isGoodsEnough = true;
String itemList = "";
while (isGoodsEnough) {
System.out.print("Введите название товара: ");
String itemName = scanner.next();

boolean validCost = false;
while (!validCost) {
System.out.print("Введите стоимость товара (в формате рубли.копейки): ");
if (scanner.hasNextDouble()) {
double itemCost = scanner.nextDouble();
if (itemCost >= 0) {
totalValue += itemCost;
itemList += itemName + " - " + String.format("%.2f", itemCost) + " руб." + "\n";
System.out.println("Товар " + itemName + " успешно добавлен.");
validCost = true;
} else {
System.out.println("Стоимость товара не может быть отрицательной.");
}
} else {
System.out.println("Введите корректное число!");
scanner.next();
}
}

System.out.print("Хотите добавить ещё один товар? (Введите \"Завершить\", чтобы закончить): ");
String userChoice = scanner.next();
if (userChoice.equalsIgnoreCase("Завершить")) {
isGoodsEnough = false;
}
}

System.out.println("Добавленные товары: ");
System.out.println(itemList);
return itemList;
}

public static double getCostPerPerson(String itemList, int guests) {
double totalValue = 0;
String[] items = itemList.split("\n");
for (String item : items) {
String costString = item.substring(item.lastIndexOf(" ") + 1, item.lastIndexOf(" руб."));
totalValue += Double.parseDouble(costString);
Comment on lines +81 to +82
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Весьма интересное решение.
В любом случае, приложение может падать из-за неверно определенного индекса item.lastIndexOf(" ") + 1. Начиная с конца, этот метод вернет индекс пробела, который стоит перед "руб.", вдобавок к этому индексу прибавляем +1. Далее определяем индекс item.lastIndexOf(" руб."), с которого начинается " руб."

Получается такая картина
Снимок экрана 2023-04-09 211153

Ошибка возникает из-за того, что мы пытаемся из строки выдернуть отрезок с 13 по 12 индекс. Можно внести исправления таким образом и будет работать:

String costString = item.substring(item.indexOf(" ") + 2, item.lastIndexOf(" руб."));
totalValue += Double.parseDouble(costString.replace(",", "."));

Но все также получится не очень хороший способ. По сути костыль)

По хорошему, ты мог в классе Calculator создать статичные переменные. Например вот такие

class Calculator {
    public static String itemList;
    public static int guests;
    public static int totalValue;

Куда сложил бы все необходимое для вычислений и парсить строки, чтобы вычленить оттуда число не пришлось бы. Но все же плюс, за такую идею)

На доработку не буду отправлять, т.к. остальное работает как часы. Просто внеси исправления, которые я тебе предложил

}
return totalValue / guests;
}

public static String getRubleSuffix(double costPerPerson) {
int rubles = (int) costPerPerson;
int lastDigit = rubles % 10;
int lastTwoDigits = rubles % 100;
if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
return "рублей";
} else if (lastDigit == 1) {
return "рубль";
} else if (lastDigit >= 2 && lastDigit <= 4) {
return "рубля";
} else {
return "рублей";
}
}
}