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
100 changes: 97 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,102 @@
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.lang.Math;
public class Main {

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
ArrayList<String> items;
ArrayList<Double> price;
int humans=-1;
int amount=0;
double sum2=0.0;
boolean bPrice = false;
Scanner scanner = new Scanner(System.in);
Calculator calculator = new Calculator();
items = new ArrayList<String>();
price = new ArrayList<Double>();
Comment on lines +16 to +17
Copy link
Copy Markdown

@ilshat-abdulin ilshat-abdulin Feb 13, 2023

Choose a reason for hiding this comment

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

🍏 В данном случае, можно сразу присвоить new ArrayList() при объявлении переменных

double d=0.0;
String s = "Что-то";
Comment on lines +18 to +19
Copy link
Copy Markdown

@ilshat-abdulin ilshat-abdulin Feb 13, 2023

Choose a reason for hiding this comment

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

🍏 Сходу не понять по названиям, для чего эти переменные. Лучше стараться именовать осмысленными, но краткими названиями

amount = 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.

🍏 Выше ноль для amount уже присвоен.

System.out.println("На скольких человек необходимо разделить счёт?");
while (humans <= 1) {
try{
humans = scanner.nextInt();
} catch (InputMismatchException ex) {
System.out.println("Вы не ввели целое положительное число.");
scanner.next();
bPrice=true;
}
if ((humans == 1)&&!(bPrice)) {
System.out.println("Количество человек, введённых пользователем, равно 1. В этом случае нет смысла ничего считать и делить.");
} else if((humans <= 1)&&!(bPrice)){
System.out.println("Количество человек меньше 1. Это некорректное значение для подсчёта.");
}
bPrice=false;
}
scanner.nextLine();
while (true) {
System.out.println("Введите название продукта.");
s = scanner.nextLine();
items.add(s);
if((s.equalsIgnoreCase("Завершить"))){
break;
}
System.out.println("Введите цену продукта.");
while (!(bPrice)){
try{
d = scanner.nextDouble();
bPrice=true;
} catch (InputMismatchException ex) {
System.out.println("Вы не ввели численное значение.");
scanner.next();
}
}
Comment on lines +46 to +54
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🍏 Использование такого рода флагов, как bPrice, полезно. Но здесь кажется лишним. Все и так работает, если обойтись без неё, просто объявив while(true). Это было бы необходимо, если бы были какие-то промежуточные шаги цикла, на которых не нужен ввод цены продукта.

Аналогично, использование bPrice выше при вводе количества гостей, также выглядит излишним

В общем тут как удобно, но лучше стараться делать как проще)

scanner.nextLine();
bPrice=false;
price.add(d);
amount++;
System.out.println("Введите 'Завершить', если вы хотите произвести расчёт");
}
scanner.close();
System.out.println();
sum2=calculator.sum(amount, price, items);
calculator.finalCalcutation(sum2,humans);
}
}
class Calculator{
int round;
double am;

double sum(int amount, ArrayList<Double> price, ArrayList<String> items){
double sum = 0.0;
for (int i=0; i<amount;i++){
System.out.println(items.get(i));
am = price.get(i);
rU(am);
System.out.println("Цена: "+price.get(i)+rU(am));
sum = Double.sum(sum, (Double) price.get(i));
}
return sum;
}

void finalCalcutation(double yeah, int humans){
System.out.println("Сумма: "+yeah+rU(yeah));
System.out.println();
System.out.println("На одного человека: "+(yeah/humans)+rU(yeah/humans));
}
String rU(double eternal){
this.round=(int) eternal;
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(this.round%100==11||this.round%100==12||this.round%100==13||this.round%100==14||this.round%100==15||this.round%100==16||this.round%100==17||this.round%100==18||this.round%100==19){
return" рублей";
Comment on lines +90 to +91
Copy link
Copy Markdown

@ilshat-abdulin ilshat-abdulin Feb 13, 2023

Choose a reason for hiding this comment

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

🍏 Работает 👍
Можно еще проще - вычислить предпоследний знак, т.е. число 1 от 114.
Остаток от деления на 100 поделить на 10 (остаток от деления на 10 будет отброшен) и проверить на равенство 1.

}else{
if(round%10==1){
return " рубль";
}else if(round%10==2||round%10==3||round%10==4){
return " рубля";
}else{
return " рублей";
Comment on lines +93 to +98
Copy link
Copy Markdown

@ilshat-abdulin ilshat-abdulin Feb 13, 2023

Choose a reason for hiding this comment

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

🍏 Такую цепочку из if-then-else можно заменить на switch

}
}
}
}