Skip to content
Merged
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
16 changes: 16 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

import java.util.Scanner;
public class Calculator {

String itemNameList = "";
int numItems;
float price;


Calculator (String itemNameList, float price, int numItems ) {

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.itemNameList = itemNameList;
this.price = price;
this.numItems = numItems;
}

}
51 changes: 47 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,51 @@
// dev branch for Y.Practicum


import java.util.Scanner;

public class Main {

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

Scanner scanner = new Scanner(System.in);
Calculator calcPersonBill = new Calculator("", 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.

⏫ Можно для полей класса Calculator проинициализировать дефолтными значениями внутри самого класса без необходимости передавать их в конструкторе

checkAndFormat checker = new checkAndFormat();
//System.out.println("Привет мир!!!");
System.out.println("На сколько человек желаете разделить счёт?");

// проверка ввода на тип int
int numPerson = checker.checkPersonVal();

while (true) {
System.out.println("Введите Название товара");

calcPersonBill.itemNameList = calcPersonBill.itemNameList + "\n" + scanner.nextLine(); // добавляем имя в строку

System.out.println("Введите цену товара");

calcPersonBill.price = calcPersonBill.price + checker.checkItemVal(); // Складываем полученые цены по мере ввода
//scanner.nextLine(); // специфичный метод для завершения ввода...

System.out.println("Товар добавлен");
System.out.println("Еще добавим?");

if ((scanner.nextLine()).equalsIgnoreCase("Завершить")) { // проверка если пользователь завершил ввод
break;
} else calcPersonBill.numItems++;
}
float eachPrice = calcPersonBill.price/numPerson;

System.out.print("Добавленные товары:");
System.out.println(calcPersonBill.itemNameList);
System.out.println(" ");

//String totalSum = "Общая сумма товаров: %.2f";
System.out.print("Общая сумма товаров: ");
checker.moneyUnitformat(calcPersonBill.price); // печать суммы товаров правильным с окончанием рублей

System.out.print("Сумма к оплате с человека: ");
checker.moneyUnitformat(eachPrice); // печать Сумма к оплате с человека правильным с окончанием рублей

}
}
}

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

public class checkAndFormat {


// Обработка слова Рубль и вывод на печать
public static void moneyUnitformat (float Munit) {
String money = "";
//String totalSum = "Общая сумма товаров: %.2f";

int iMunit = (int)Munit;
int mCh = iMunit%10;

if (iMunit%100>=11 && iMunit<=14) {
money = "%.2f рублей";
System.out.println(String.format(money, Munit));
} else {
switch (mCh) {
case 1:
money = "%.2f рубль";
System.out.println(String.format(money, Munit));
break;
case 2:
case 3:
case 4:
money = "%.2f рубля";
System.out.println(String.format(money, Munit));
break;
default:
money = "%.2f рублей";
System.out.println(String.format(money, Munit));
}
}
}
// функция проверки корректности ввода количества человек и далее вывода в main
public static int checkPersonVal() {
Scanner scanner = new Scanner(System.in);
while (true) {
if (!scanner.hasNextInt()) {
System.out.println("Извините, но это явно не число. Введите число и попробуйте снова!");
scanner.nextLine();}
else break;
}

int numPerson = scanner.nextInt();
scanner.nextLine();

while (true) {
if (numPerson <= 1) {
System.out.println("Значение не подходит, введите другое значение");
numPerson = scanner.nextInt();
scanner.nextLine(); // специфичный метод для завершения ввода...
}
else break;
}
return numPerson;
}

// функция проверки корректности ввода цены товара и далее вывода в main
public static float checkItemVal() {
Scanner scanner = new Scanner(System.in);
while (true) {
if (!scanner.hasNextFloat()) {
System.out.println("Извините, но это явно не число. Введите число и попробуйте снова!");
scanner.nextLine();}
else break;
}
float Item = scanner.nextFloat();
scanner.nextLine(); // специфичный метод для завершения ввода...

while (true) {
if (Item < 0) {
System.out.println("Значение не подходит, введите другое значение");
Item = scanner.nextInt();
scanner.nextLine();
}
else break;
}
return Item;
}


}