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
67 changes: 67 additions & 0 deletions src/main/java/Calculate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
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 принят определенный стиль форматирования кода. Если не вдаваться в подробности, то отформатировать код можно быстрой комбинаций клавиш Ctrl+Alt+L(Windows) или  (⌘+⌥+L)(Mac)

import java.util.Scanner;

public class Calculate {
static Scanner scanner = new Scanner(System.in);
static List<GoodData> goods = new ArrayList<>();

public static List<GoodData> getGoods() {
while (true) {
System.out.println("Добавить новый товар? Если да, то напишите любой символ, если нет, введите завершить...");
String answer = scanner.next();
if (answer.equalsIgnoreCase("завершить")) {
if (goods.size() < 1) {
System.out.println("Нужно добавить хотя бы 1 товар");
} else {
System.out.println("Добавленные товары:");
for (GoodData good : goods) {
System.out.println("наименование товара: " + good.goodName + " стоимость: " + good.goodCost);
}
return goods;
}
} else {
String goodName = getGoodName();
Double goodCoast = getGoodCoast();
GoodData item = new GoodData(goodName, goodCoast);
goods.add(item);
System.out.println("наименование товара: " + goods.get(goods.size() - 1).goodName + " стоимость: " + goods.get(goods.size() - 1).goodCost);
}
}
}

public static String getGoodName() {
System.out.println("Введите наименование товара");
return scanner.next();
}

public static Double getGoodCoast() {
System.out.println("Введите цену товара");
double coast = 0.0;
while (true) {
if (scanner.hasNextDouble()){
coast = scanner.nextDouble();
if (coast > 0){
return Double.parseDouble(String.format("%.2f", coast).replace(',', '.'));
} else {
System.out.println("Цена товара не может быть отрицательной или равной 0, повторите ввод");
continue;
}
}
System.out.println("Цена товара должна быть указана в дробном формате 'x.xx' ");
scanner.next();
}
}


public static class GoodData {
private final String goodName;
final Double goodCost;

public GoodData(String goodName, Double goodCost) {
this.goodName = goodName;
this.goodCost = goodCost;
}
}
}
26 changes: 26 additions & 0 deletions src/main/java/Guests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import java.io.Serializable;
import java.util.Scanner;

public class Guests {
static 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.close() после того, как сканнер больше не используется. Это необходимо для того, что бы этот объект не потреблял ресурсы, тогда когда это уже не требуется.


public static int getPerson() {
int count = 0;
System.out.println("На скольких человек необходимо разделить счёт?");
while (true) {
if (scanner.hasNextInt()) {
count = scanner.nextInt();
if (count > 1) {
System.out.println("Тогда будем считать");
break;
} else {
System.out.println("Число не должно быть отрицательным или равным 0, повторите ввод");
continue;
}
}
System.out.println("Ошибка, введите корректное значение гостей");
scanner.next();
}
return count;
}
}
28 changes: 27 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import java.util.List;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
int persons = Guests.getPerson();
System.out.println("Количество человек: " + persons);
List<Calculate.GoodData> goods = Calculate.getGoods();
double averagePrice = 0.0;
for (Calculate.GoodData good : goods) {
averagePrice += good.goodCost;
}

double finalCoast = averagePrice / persons;
printResult(finalCoast);
}

private static void printResult(double price) {
String format = String.valueOf((int) price);
int preLastDigit = Integer.parseInt(format) % 100 / 10;
if (preLastDigit == 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 принят немного другой стиль форматирования кода. Если не вдаваться в детали, то легко и быстро отформатировать код в Android Studio можно следующей комбинацией клавиш: в Windows Ctrl + Alt + L , в MacOs ⌘ + ⌥ + L.

System.out.println("Сумма к оплате: " + String.format("%.2f", price) + " рублей");
return;
}
switch (Integer.parseInt(format) % 10) {
case 1 -> System.out.println("Сумма к оплате: " + String.format("%.2f", price) + " рубль");
case 2, 3, 4 -> System.out.println("Сумма к оплате: " + String.format("%.2f", price) + " рубля");
default ->
System.out.println("Сумма к оплате: " + String.format("%.2f", price) + " рублей");
}
}
}