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
73 changes: 72 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,77 @@
/*
«Калькулятор счёта» — консольное приложение,
которое будет задавать вопросы в консоли,
считывать пользовательский ввод
и в результате показывать
список товаров и сумму для каждого из друзей.
*/

import java.util.Scanner;
public class Main {
private static final Scanner scanner = new Scanner(System.in);

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

int k;
do {
System.out.println("Укажите, на скольких человек делим счет.\nВыберете значение больше 1:");
while (!scanner.hasNextInt()) {
System.out.println("Напишите значение целым числом, не используйте буквы.");
scanner.next();
}
k = scanner.nextInt();
} while (k <= 1);
System.out.println("Замечательно! Количество человек - " + k +"\n\nТеперь укажи товары и их цены. Или напиши 'завершить' для рассчета.");


String end = "завершить";
String text = "";
Double pr = 0.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.

Можно не присваивать начальное значение.

String list = "";
Double sum = 0.0;


while (!text.equalsIgnoreCase(end)) {
System.out.println("Товар, например, 'Тыквенный раф' -");
scanner.nextLine();
text = scanner.nextLine();
if (text.equalsIgnoreCase(end)) {break;}
list = list + "\n" + text;
System.out.println(text + " - записали\n");

do {
System.out.println("Укажите цену (больше нуля). Например, '150,10' - ");
while (!scanner.hasNextDouble()) {
System.out.println("Не используйте буквы, указывайте запятую для нецелых чисел.");
scanner.next();
}
pr = scanner.nextDouble();
} while (pr < 0.0);
System.out.println(pr + " - ок, посчитали\n");
sum += pr;

Sku sku = new Sku(text, pr);
}

if (list.isEmpty()) {
System.out.println("Ничего не заказано"); return;
}


System.out.println("\n*****************\nСписок всех товаров:" + list.substring(0, list.length()) + "\n\nОбщая сумма: " + sum + " Количество человек: " + k + "\n");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

list.substring(0, list.length()) - это и есть весь list.

Double pay = sum / k;
String payment = String.format("%.2f", pay);
String rub = "";

System.out.println("*****************\nСумма на каждого: ");
Rubl r = new Rubl(payment, pay);
r.rublCorrect(payment, pay, rub);
System.out.println("*****************");


}
}
53 changes: 53 additions & 0 deletions src/main/java/Rubl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
public class Rubl {
String sumStr;
Double sumDouble;
String rubSogl;

Rubl(String sumStr, Double sumDouble) {
this.sumStr = sumStr;
this.sumDouble = sumDouble;
}

public static void rublCorrect(String sumStr, Double sumDouble, String rubSogl) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Аргумент rubSogl передается, но не используется. Стоит убрать

if (sumDouble <= 10) {
//System.out.println("меньше 10");
switch (sumStr.substring(sumStr.length() - 4, sumStr.length() - 3)) {
case "1":
rubSogl = "рубль";
break;
case "2":
case "3":
case "4":
rubSogl = "рубля";
break;
default:
rubSogl = "рублей";
break;
}
System.out.println(sumStr + " " + rubSogl);
} else if (sumDouble > 10) {
//System.out.println("больше 10");
if (sumStr.substring(sumStr.length() - 5, sumStr.length() - 4).equals("1")) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно все это условие заменить на sumStr.charAt(sumStr.length() - 5) == '1'. Студия подсказывает эту оптимизацию

rubSogl = "рублей";
System.out.println(sumStr + " " + rubSogl);
return;
}
switch (sumStr.substring(sumStr.length() - 4, sumStr.length() - 3)) {

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 "1":
rubSogl = "рубль";
break;
case "2":
case "3":
case "4":
rubSogl = "рубля";
break;
default:
rubSogl = "рублей";
break;
}

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(sumStr + " " + rubSogl);
}
}
}


12 changes: 12 additions & 0 deletions src/main/java/Sku.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public class Sku {
String name; //название товара
double price; // цена товара
public static int goodsCount;

//теперь делаем конструктор для товара
Sku(String nameSKU, double priceSKU){
name = nameSKU;
price = priceSKU;
goodsCount++;
}
}