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.

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.

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

9 changes: 9 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.

13 changes: 13 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
public class Calculator {
float sum;
String items;
Calculator() {
items = "";
sum = 0;
}
public void addItem( float price , String product) {
sum = sum + price;
items = items + product + "\n";
}
}

78 changes: 75 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,80 @@
import java.util.Scanner;

public class Main {

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Поскольку по умолчанию неинициализированная переменная типа int будет равна 0, можно не писать = 0

while (true) {
System.out.println("На скольких человек будет разделен счет?:");
if (scanner.hasNextInt()) {
person = scanner.nextInt();
} else {
System.out.println("Количество человек должно быть целым числом");
scanner.next();
continue;
}
if (person < 1) {
System.out.println("Количество человек меньше 1. Это некорректное значение для подсчёта.");
} else if (person == 1) {
System.out.println("Количество человек равно 1. В этом случае нет смысла ничего считать и делить.");
} else {
break;
}
}
Calculator calculator = new Calculator();
float price = 0;
String product = "";
String command = "";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь тоже все переменные такими и будут по умолчанию, поэтому этими значениями можно не инициализировать

while (true) {
System.out.println("Введите стоимость и товар:");
if (scanner.hasNextFloat()) {
price = scanner.nextFloat();
} else {
System.out.println("Стоимость должна быть числом");
scanner.next();
continue;
}
product = scanner.next();
calculator.addItem(price, product);
System.out.println("Товар добавлен в счет");
System.out.println("Общаая сумма:" + calculator.sum + "Товары:" + calculator.items);
System.out.println("Хотите еще добавить тровар? Если нет, то введите команду \"Завершить\"");
command = scanner.next();
if (command.equalsIgnoreCase("Завершить")) {
break;
}
}
System.out.println("Итоговый счет:\n" + calculator.items);
int list = (int) Math.floor(calculator.sum / (double) person);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше назвать переменную более очевидно

if (list == 1) {
System.out.println(String.format("Сумма на одного человека:%.2f рубль", calculator.sum / (double) person));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Код calculator.sum / (double) person повторяется много раз, лучше посчитать один раз и использовать переменную

} else if (2 <= list && list <= 4) {
System.out.println(String.format("Сумма на одного человека:%.2f рубля", calculator.sum / (double) person));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вся строчка System.out.println(String.format("Сумма на одного человека:%.2f рубля", calculator.sum / (double) person));, за исключением самого слова "рубля" повторяется много раз, лучше вынести её за пределы if-else, а в нем определять только само слово

} else if (5 <= list && list <= 20) {
System.out.println(String.format("Сумма на одного человека:%.2f рублей", calculator.sum / (double) person));
} else {
int digit = list % 10;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно было бы оставить только switch, без верхнего if-else. Для случаев, когда list <= 10 и когда list >= 20, нам нужна только последняя цифра для определения падежа, для этого можно использовать digit = list % 10 (если будет меньше 10, результат будет равен самому list), и в одном switch проверять цифру. А до него ещё с помощью одного if проверять только, что list % 100 больше 10 и меньше 20

switch (digit) {
case 0:
case 6:
case 9:
case 8:
case 7:
case 5:
System.out.println(String.format("Сумма на одного человека:%.2f рублей", calculator.sum / (double) person));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Поскольку здесь много case, можно их объединить, используя default в конце

break;
case 1:
System.out.println(String.format("Сумма на одного человека:%.2f рубль", calculator.sum / (double) person));
break;
case 2:
case 4:
case 3:
System.out.printf("Сумма на одного человека:%.2f рубля%n", calculator.sum / (double) person);
break;
}
}

}
}