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
20 changes: 20 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Calculator {

String listOfGoods = "";
double totalPrice = 0;

public void formAListOfGoodsAndTheirPrice() {
while (true) {
Item item = new Item();
String nameOfItem = item.addAnItem();
double priceOfItem = item.addAnItemPrice();
listOfGoods += nameOfItem + " " + String.format("%.2f", item.priceOfItem) + "\n";
totalPrice += priceOfItem;
System.out.println("Товар успешно добавлен! Вы хотите добавить еще товар?");
System.out.println("Введите команду \"Завершить\" для того, чтоб завершить процесс добавления товаров.");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Такие подряд идущие println можно объединить в один.

String addOneMore = Main.sc.nextLine();
if (addOneMore.equalsIgnoreCase("завершить")) break;
}
}

}
19 changes: 19 additions & 0 deletions src/main/java/IsItANumber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//Класс для проверки является ли введенный символ (символы) неотрицательным целым или вещественным числом.
public class IsItANumber {

public boolean naturalNum(String str) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В этой программе уже было использовано ключевое слово static, можно также сделать эти методы тоже static, так как они служебные. Тогда нам не нужно будет создавать экземпляр класса IsItANumber для вызова его методов

for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) return false;
}
return true;
}

public boolean doubleNum(String str) {
int nubmerOfDots = 0;
for (char c : str.toCharArray()) {
if (c == '.') nubmerOfDots += 1;
if (!(Character.isDigit(c) || c == '.') || nubmerOfDots > 1) return false;
}
return true;
}
}
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.nextInt(), nextDouble()

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

String nameOfItem;
double priceOfItem;

public String addAnItem() {
System.out.println("Введите название товара.");
nameOfItem = Main.sc.nextLine();
return nameOfItem;
}

public double addAnItemPrice() {
IsItANumber checkedString = new IsItANumber();
System.out.println("Введите стоимость товара в формате \"рубли.копейки\".");
while(true) {
String priceOfItem = Main.sc.nextLine();
if (!(checkedString.doubleNum(priceOfItem))) {
System.out.println("Ошибка: \"Введен недопустимый символ или отрицательное число!\" Повторите ввод стоимости товара в виде числа!");
}
else {
this.priceOfItem = Double.parseDouble(priceOfItem);
return this.priceOfItem;
}
}
}

}
40 changes: 36 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,40 @@
import java.util.Scanner;
public class Main {
public static Scanner sc = new Scanner(System.in);

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

Choose a reason for hiding this comment

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

Лучше внести этот принтлн в метод correctedPersonsNumber, потому что это часть той логики

int personsNumber = correctedPersonsNumber();

//Вторая часть задачи (формирование списка продуктов и подсчет их общей суммы):
Calculator calculator = new Calculator();
calculator.formAListOfGoodsAndTheirPrice();

//Третья часть задачи (вывод списка товаров и суммы, которую должен заплатить каждый человек):
System.out.println("Добавленные товары:\n" + calculator.listOfGoods);
System.out.printf("С каждого %.2f %s!%n", calculator.totalPrice / personsNumber, rubInCorrectCase(calculator.totalPrice / personsNumber));
}

public static int correctedPersonsNumber() {
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 принята конвенция, согласно которой методы принято называть глаголами, см. https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html

IsItANumber checkedInput = new IsItANumber();
while (true) {
String personsNumber = sc.nextLine();
if (!checkedInput.naturalNum(personsNumber)) {
System.out.println("Ошибка: \"Введен недопустимый символ или отрицательное число!\" Повторите ввод!");
} else if (Integer.parseInt(personsNumber) <= 1) {
System.out.println("Ошибка: \"Введенное количество человек меньше двух\"! Повторите ввод!");
} else return Integer.parseInt(personsNumber);
}
}
}

public static String rubInCorrectCase(double sumOfEachPerson) {
int a = (int) sumOfEachPerson;
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 rub;
if (a%10 == 1 && a%100 != 11) rub = "рубль";
else if ((a%10 >= 2 && a%10 <= 4) && (a%100 != 12 && a%100 != 13 && a%100 != 14)) rub = "рубля";
else rub = "рублей";
return rub;
}

}