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
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 123 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions src/main/java/CaseEnding.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class CaseEnding {

static String roubleCase = " рублей";

Choose a reason for hiding this comment

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

Переменную можно убрать, и ниже при возврате результата писать просто return " <нужное слово>";. Или оставить переменную, но убрать здесь инициализацию, в каждом if убрать return, оставить только присваивание переменной нужного слова, а после всех if-else поставить return roubleCase;

static double remainder;

static String setEnding(double price) {
if (Math.floor(price) >= 11 && Math.floor(price) <= 14) {

Choose a reason for hiding this comment

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

Если здесь добавить деление по модулю на 100 Math.floor(price) % 100, то для 111, 211 и т.д. будет работать тоже

return roubleCase = " рублей";
} else {
remainder = Math.floor(price) % 10;

Choose a reason for hiding this comment

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

Math.floor(price) считается 3 раза, можно посчитать 1 раз и записать в переменную

if (remainder == 1) {
return roubleCase = " рубль";
} else if (remainder >= 2 && remainder <= 4) {
return roubleCase = " рубля";
} else {
return roubleCase = " рублей";
}
}
}
}
53 changes: 53 additions & 0 deletions src/main/java/Item.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import java.util.Scanner;

public class Item {

static String name;
Copy link

@MagicUnderHood MagicUnderHood Nov 6, 2022

Choose a reason for hiding this comment

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

Все модификаторы static можно в этом классе убрать, а при вызове метода calculate в Main сначала создавать объект класса Item. Подробнее про static будет в следующих уроках, пока в нем сильной необходимости нет

static double price = 0;

static String values = "";
static double sum = 0;

static void calculate() {

Choose a reason for hiding this comment

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

Можно результатом этого метода возвращать посчитанную sum, тогда не надо будет её использовать в Main, код будет выглядеть логичнее

while (true) {

Scanner scanner = new Scanner(System.in);

System.out.println("\nЕсли вы хотите добавить блюдо в калькулятор, введите наименование блюда:");
System.out.println("Если вы не хотите добавлять блюдо в калькулятор, введите «Завершить»:");

name = scanner.nextLine();

if (name.equalsIgnoreCase("завершить")) {
System.out.println("Выход из калькулятора (вы ввели «Завершить»).");
break;
} else {
System.out.println("Введите стоимость блюда в формате [рубли.копейки]:");

String stringPrice = scanner.nextLine();

try {
price = Double.parseDouble(stringPrice);
} catch (NumberFormatException e) {
System.out.println("Введите численное значение.");
price = 0;
}

if (price > 0) {
values += name + " " + price + ";\n";
sum += price;

System.out.println("Блюдо " + name + " стоимостью " + price + CaseEnding.setEnding(price) + " успешно добавлено!");
System.out.println("Текущая сумма блюд: " + sum + CaseEnding.setEnding(sum) + ".");
} else {
System.out.println("Введите корректную стоимость блюда больше нуля.");

}
}
}

System.out.println("\nДобавленные блюда: ");
System.out.println(values);
System.out.println("Общая сумма блюд: " + sum + CaseEnding.setEnding(sum) + ".");
}
}
45 changes: 42 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,47 @@
import java.util.Scanner;

public class Main {

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

Scanner scanner = new Scanner(System.in);

while (true) {

printMenu();

Choose a reason for hiding this comment

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

Можно этот вывод вынести до while, тогда он будет печататься один раз, в принципе этого достаточно для пользователя


String quantityOfPersons = scanner.nextLine();
int number = -1;

try {
number = Integer.parseInt(quantityOfPersons);
} catch (NumberFormatException e) {
System.out.println("Вы ввели что-то не то... Давайте ещё раз.");
}

if (number == 1) {
System.out.println("Тебе грустно и одиноко, нечем заняться? Занимайся Джаббой!");
} else if (number > 1) {
System.out.println("Итак, вас " + quantityOfPersons + ". И вы харчевали...");
Item.calculate();
double pricePerPerson = Item.sum / number;
System.out.println("\nКаждый из посетителей должен заплатить " + String.format("%.2f", pricePerPerson) + CaseEnding.setEnding(pricePerPerson) + ".");
System.out.println("Вычисления завершены. Выход.");
break;
} else if (number == 0) {
System.out.println("Выход, потому что кое-кто нажал ноль.");
break;
} else {
System.out.println("Введите положительное число гостей.");
}

}
}

public static void printMenu() {
System.out.println("\nДобрый день!");
System.out.println("На скольких человек вы хотите разделить счёт?");
System.out.println("Пожалуйста, введите количество гостей - от 1 и выше.");
System.out.println("Или введите 0 для того, чтобы выйти из программы.");
}
}