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
44 changes: 44 additions & 0 deletions src/main/java/Calculate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import java.util.Scanner;

public class Calculate {
static String allItem = ""; //Строка с названиями всех товаров
static double allPrice = 0.0; //счётчик общей цены
static int i = 0; //счётчик количества товаров

public static void calculate() {
Scanner scanner = new Scanner(System.in);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучшее переиспользовать инстанс Scanner, а не создавать каждый раз новый.

Item item= new Item(" ", 0);
System.out.println("Введите название товара:");

while (true) {
item.name = scanner.next();
scanner.nextLine();
if (item.name.equalsIgnoreCase("завершить")) {
System.out.println("Вы завершили ввод товаров");
break;
} else {
//проверка на число и положительность числа
while (true) {
System.out.println("Введите стоймость товара в формате '00,00':");
if (scanner.hasNextDouble()) {
item.price = scanner.nextDouble();
scanner.nextLine();
if (item.price > 0) {
System.out.println("Товар добавлен. Вы можете добавить ещё один товар. Для подсчёта введите 'завершить'");
allItem = allItem.concat(item.name).concat("\n");
allPrice += item.price;
i++;
break;
}
if (item.price <= 0) {
System.out.println("Пожалуйста, введите положительное число.");
}
} else {
System.out.println("Пожалуйста, используйте числа.");
scanner.nextLine();
}
}
}
}
}
}
22 changes: 22 additions & 0 deletions src/main/java/Format.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public class Format {
public static String GetRuble(double num){
int desayt = ((int) num % 100) / 10;
if (desayt == 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.

В Java переносить открывающую фигурную скобку в if/switch/методе не нужно

return "рублей";
}

switch ((int)num % 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.

Чтобы не дублировать приведение типов (int)num можно сделать один раз и сохранить результат в переменную

{
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
return "рублей";
}
}

}
9 changes: 9 additions & 0 deletions src/main/java/Item.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Item {
String name;
double price;

Item(String itemName, double itemPrice){
name = itemName;
price = itemPrice;
}
}
37 changes: 34 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,39 @@
import java.util.Scanner;

// dev branch for Y.Practicum
public class Main {

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
Scanner scanner = new Scanner(System.in);
int people;
System.out.println("Добрый день! На сколько людей надо разделить счёт?");
while(true) {
if (scanner.hasNextInt()) {
people = scanner.nextInt();
if (people == 1) {
System.out.println("Введите количество людей больше одного:");
}
if (people < 1) {
System.out.println("Введите корректное количество людей:");
}
if (people > 1){
break;
}
} else {
System.out.println("Пожалуйста, введите количество людей, используя число:");
scanner.nextLine();
}
}
Calculate.calculate();

double personMoney = Calculate.allPrice / people;
String tempPrice = "Всего сумма: %.2f";
String tempPerson = "На каждого человека: %.2f";

System.out.println("Добавленные товары:\n" + Calculate.allItem);
System.out.println("Всего людей: " + people);
System.out.println(String.format(tempPrice, Calculate.allPrice) + " " + Format.GetRuble(Calculate.allPrice));

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.format можно избавиться от конкатенации через оператор +, подставив нужные параметры в паттерн

System.out.println(String.format(tempPerson, personMoney) + " " + Format.GetRuble(personMoney));

}
}