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
16 changes: 16 additions & 0 deletions src/main/java/Bill.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
public class Bill {
String list = "";
double total = 0.0;
void addToTotal (double itemCost){
total += itemCost;
}
void addToList (String itemName){
list += "\n- " + itemName;
}
void displayTotalCost (){
System.out.printf("Общая стоимость внесённых позиций: %.2f",total);
}
void displayTotalList (){
System.out.println("Список внесённых позиций:" + list);
}
}
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 @@
public class Calculator {
double billPerPerson;
Calculator(int persons, Bill bill) {
billPerPerson = bill.total;
if (persons > 1) {
billPerPerson = bill.total / persons;
System.out.printf("Каждый из %d присутствующих должен заплатить: %.2f", persons, billPerPerson);
}else
System.out.printf("Вы оплачиваете полную стоимость: %.2f", billPerPerson);
}

Calculator() {
System.out.println("Для рассчёта передайте в качестве аргументов количество человек и объект класса Bill");
}
}

89 changes: 88 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,95 @@
import java.util.PrimitiveIterator;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
Scanner scanner = new Scanner(System.in);
System.out.print("Введите количество человек, между которыми нужно разделить счёт: ");
int persons;
String input = scanner.next();

// защита от присваивания некорректных значений
while (!isValidInt(input)) {

Choose a reason for hiding this comment

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

У Scanner есть удобный метод hasNextInt, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку как int

System.out.print("\nНекорректное число! Количество человек должно быть целым, положительным числом! Попробуйте ещё раз: ");
input = scanner.next();
}
persons = Integer.parseInt(input);

Bill bill = new Bill();
String completion = "";
while (completion.compareToIgnoreCase("Завершить") != 0) {

Choose a reason for hiding this comment

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

Можно просто equalsIgnoreCase

System.out.print("\nВведите название товара: ");
bill.addToList(scanner.next());
System.out.print("Введите стоимость товара: ");
input = scanner.next();
while (!isValidDouble(input)) {

Choose a reason for hiding this comment

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

По аналогии с int у Scanner есть метод hasNextDouble
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#hasNextDouble%28%29

System.out.print("\nНекорректное число! Стоимость должна быть выражена положительным числом (разделитель целой и дробной части - точка)! Попробуйте ещё раз: ");
input = scanner.next();
}
bill.addToTotal(Double.parseDouble(input));
System.out.print("Товар успешно добавлен в список! Хотите добавить ещё что-нибудь? (Для рассчёта равных долей введите \"Завершить\"): ");
completion = scanner.next();
}
System.out.println("-----------------------------------------------------");
bill.displayTotalList();
System.out.println("----------");
bill.displayTotalCost();
System.out.println(" " + messageEndingHandler(bill.total));
System.out.println("-----------------------------------------------------");
Calculator payment = new Calculator(persons,bill);
System.out.println(" " + messageEndingHandler(payment.billPerPerson));
}

// проработка окончания слова "рубль" в зависимости от суммы
public static String messageEndingHandler(double number) {
String ending;
String message = "рубл";
int preLastDigit = (int) number % 100 / 10;
if (preLastDigit == 1)
{
ending = "ей";
}
switch ((int) number % 10)
{
case 1:
ending = "ь";
break;
case 2:
case 3:
case 4:
ending = "я";
break;
default:
ending = "ей";
break;
}
return message += ending;
}

// проверка значения на целочисленность и положительность
public static boolean isValidInt(String str){
if (str != null && str.matches("[0-9]+") ) {
if (Integer.parseInt(str) <= 0 ) {
return false;
} else
return true;
} else
return false;
}

// проверка значения на вещественность и положительность
public static boolean isValidDouble(String str){
if (str != null && str.matches("[0-9.]+") ) {
if (Double.parseDouble(str) <= 0 ) {
return false;
} else
return true;
} else
return false;
}
}