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

class CountingPeople { // Метод спрашивает кол-во людей для выставления счета;
int result = 0;
public int calculate() {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("На сколько человек считать счет?");
while (true) // Проверка на то, чтобы ввели именно число. Можно было бы вынести в отдельный метод. Но в контексте работы, не хотелось бы.
{
if (scanner.hasNextDouble() || scanner.hasNextLong() || scanner.hasNextInt())
{
result = Integer.parseInt(scanner.nextLine());
break;
}
else
{
System.out.println("Вы ввели не число, так на сколько человек счет считать?");
scanner.nextLine();
}}
if (result == 1) {
System.out.println("А что тут считать, 1 и есть 1");
} else if (result > 1) {
System.out.println("Понял, счет делим на " + result);
return result;
} else {
System.out.println("Это некорректное значение для подсчёта, введи снова");
}
}
while (result <= 1);
return result;
}
}
24 changes: 24 additions & 0 deletions src/main/java/Good.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
public class Good {
public double price = 0.00;
public String name = "New Good";

public String goodCreated(String name, double price) { // Метод создания товара.
this.priceSet(price);
this.nameSet(name);
String formattedDouble = String.format("%.2f", this.price); // Можно было бы вынести в отдельный метод, чтобы было DRY, но не вижу смысла;
String goodCreated = this.name + formattedDouble;
return goodCreated;
}

public double priceSet(double price) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Этот метод возвращает строку, но при этом возвращаемое значение нигде не используется - метод вызывается, в нем происходит присваивание this.price = price;, после чего return this.price; в пустоту. Лучше сделать void и ничего не возвращать

this.price = price;
// System.out.println("Price has set " + this.price);
return this.price;
}

public String nameSet(String name) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

То же самое

this.name = name;
// System.out.println("Name has set " + this.name);
return this.name;
}
}
16 changes: 13 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@

public class Main {
int result;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Переменная объявляется, но нигде не используется

public static void main(String[] args) {
System.out.println("Hello world!");
CountingPeople count = new CountingPeople(); // Отдельный класс подсчета кол-ва людей;
int result = count.calculate(); // Считаем кол-во людей;
newGoodGenerator generator = new newGoodGenerator(); // Калькулятор из задания наывается в моем решении генератором;
do{
generator.generateNewGood(); // Создаем первый товар;
} while (generator.askingMoreGoods()); // Тут спрашиваем нужны ли еще товары;
// System.out.println("Добавили все товары, какие мы хотели");
generator.showTotalPrice();
generator.bill(result); // Метод проводит расчет по покупкам;
}
}
}


90 changes: 90 additions & 0 deletions src/main/java/newGoodGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import java.util.Scanner;

public class newGoodGenerator { // Добавить с большой буквы; Классы в JAVA с большой буквы.

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 пишутся в PascalCase:)

String nameToSet = "Nameless Good";
double priceToSet = 00.00;
double totalPrice = 00.00;
public String allGoods = "Список всех товаров: " + "\n";

public String generateNewGood() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Этот метод возвращает строку, но при этом возвращаемое значение нигде не используется - метод просто вызывается без присваивания его переменной: generator.generateNewGood();. Лучше тогда сделать его void.

Scanner scanner = new Scanner(System.in);
System.out.println("Введите название товара, чтобы добавить его");
// String descriptionArrived = scanner.next(); Была ошибка, что считывал только до пробела и выкидывал ошибку.
this.nameToSet = scanner.nextLine();
do {
System.out.println("Введите цену товара, чтобы добавить ее (рубли.копейки)");
while (true) // Проверка на то, чтобы ввели положительное число. Можно было бы вынести в отдельный метод. Но в контексте работы, не хотелось бы.
{
if (scanner.hasNextDouble() || scanner.hasNextLong() || scanner.hasNextInt()) {
this.priceToSet = Double.parseDouble(scanner.nextLine());
if (this.priceToSet < 1) {
System.out.println("Вы ввели отрицательное число: " + this.priceToSet);
}
break;
} else {
System.out.println("Вы ввели не число, повторите");
scanner.nextLine();
}
}
} while (this.priceToSet <= 1);
Good goodToSend = new Good(); // Создаем новый товар из класса Good;
String goodAdded = goodToSend.goodCreated(this.nameToSet, this.priceToSet);
this.addingNewGood(this.nameToSet, this.priceToSet);
return goodAdded;
}

public boolean askingMoreGoods() { //
Scanner scanner = new Scanner(System.in);
System.out.println("Нужны еще товары, нажмите 'Enter'. Чтобы завершить программу введите 'Завершить'");
String userReply = scanner.nextLine();
if (userReply.equalsIgnoreCase("Завершить")) // Выход из цикла по условиям задачи;
{
return false;
} else {
System.out.println("Добавляем еще один товар");
return true;
}
}

public void addingNewGood(String name, double price) {
String formattedDouble = String.format("%.2f", price); // Можно было бы вынести в отдельный метод, чтобы было DRY, но не вижу смысла;
System.out.println("Товар был добавлен в корзину: " + formattedDouble + " " + name);
String goodDescription = formattedDouble + " - " + name + "; ";
totalPrice += price;
System.out.println("Цена всего заказа: " + formattedDouble);
allGoods = allGoods.concat(goodDescription + "\n");
System.out.println(allGoods);
}

public String showTotalPrice() { // Метод показывает общую форму заказа;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Также return в пустоту

String formattedDouble = String.format("%.2f", totalPrice); // Можно было бы вынести в отдельный метод, чтобы было DRY, но не вижу смысла;
System.out.println("Цена всего заказа: " + formattedDouble);
return formattedDouble;
}

public void bill(int peopleCount) { // Метод, который выставляет счет. Он делит общую сумму на кол-во людей;
double result = totalPrice / peopleCount;
System.out.println(allGoods);
System.out.printf("Каждый человек заплатит %.2f %s", result, declinationOfRub(result));
}
public String declinationOfRub(double result){
int num = (int) result;
int preLastDigit = num % 100 / 10;
if (preLastDigit == 1)
{
return "рублей";
}
switch (num % 10)
{
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
return "рублей";
}
}

}