Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

рабочая версия калькулятора ресторанного счёта #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
BozhdayA wants to merge 1 commit into main
base: main
Choose a base branch
Loading
from master
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
9 changes: 9 additions & 0 deletions src/main/java/Good.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Good {
public String Name;
public double Price;

public Good(String goodName, double goodPrice) {
Name = goodName;
Price = goodPrice;
}
}
10 changes: 10 additions & 0 deletions src/main/java/InputValueController.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
public class InputValueController {
public static boolean IsNumberOfPeopleCorrect(int countPeople) {
return countPeople > 1;
}

public static boolean IsPriceCorrect(double price) {
return price >= 0;
}
}

62 changes: 59 additions & 3 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,8 +1,64 @@
import java.util.Scanner;

public class Main {

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

Scanner scanner = new Scanner(System.in);
boolean countPeopleIsCorrect;
do
{
System.out.println("На какое количество человек разделить счёт?");
countPeople = scanner.nextInt();
Copy link

@MagicUnderHood MagicUnderHood Dec 10, 2022

Choose a reason for hiding this comment

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

Пользователь может ввести на вопрос про количество человек вместо целого числа строку, и приложение упадет. Для стоимости товаров ты обрабатываешь такую ситуацию через hasNextDouble, стоит добавить обработку и для количества людей, чтобы приложение не падало.

// проверка введенного количества людей
countPeopleIsCorrect = InputValueController.IsNumberOfPeopleCorrect(countPeople);
if (!countPeopleIsCorrect){
System.out.println("Количество должно быть больше 1");
}
} while (!countPeopleIsCorrect);


SplitBillCalculator calculator = new SplitBillCalculator(countPeople);

while (true) {
System.out.println("Введите наименование товара или команду 'Завершить' для окончания ввода товаров");
String goodsName = scanner.next();
if (goodsName.equalsIgnoreCase("завершить"))
break;

double price;
System.out.println("Введите стоимость товара в формате 0,00");
while (true){
if (scanner.hasNextDouble()) {
price = scanner.nextDouble();
boolean isCorrect = InputValueController.IsPriceCorrect(price);
if (isCorrect)
break;
}
System.out.println("Ошибка в формате числа. Повторите ввод");
scanner.next();
}

Good good = new Good(goodsName, price);
calculator.AddGoods(good);
String rubString = currencyNameConverter.GetCorrectRubString(calculator.TotalAmount);
System.out.printf("Товар добавлен. Текущая сумма счёта %.2f %s\n", calculator.TotalAmount, rubString);
}

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

String rubString = currencyNameConverter.GetCorrectRubString(calculator.TotalAmount);
System.out.printf("Общая сумма: %.2f %s\n", calculator.TotalAmount, rubString);

double splitTotalAmount = calculator.SplitTotalAmount();
String splitRubString = currencyNameConverter.GetCorrectRubString(splitTotalAmount);
System.out.printf("Сумма с человека: %.2f %s\n", splitTotalAmount, splitRubString);

System.out.println("Для завершения нажмите любую клавишу");
scanner.next();
}
}

20 changes: 20 additions & 0 deletions src/main/java/SplitBillCalculator.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class SplitBillCalculator {

int countPeople;

public String ListOfGoods = "";
public double TotalAmount = 0;

public SplitBillCalculator(int countPeople) {
this.countPeople = countPeople;
}

public void AddGoods(Good good) {
ListOfGoods = ListOfGoods +"\n"+ good.Name;
TotalAmount = TotalAmount + good.Price;
}

public double SplitTotalAmount() {
return TotalAmount / countPeople;
}
}
26 changes: 26 additions & 0 deletions src/main/java/TotalAmountOutput.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
public class TotalAmountOutput {
public String GetCorrectRubString(double totalAmount) {
int lastDigit = GetLastIntDigit(totalAmount);

switch (lastDigit) {
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
return "рублей";
Copy link

@MagicUnderHood MagicUnderHood Dec 10, 2022

Choose a reason for hiding this comment

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

Единственное, не учтена ситуация для чисел 11-19, окончание должно быть "рублей", а сейчас дает рубля для 12-14. Для этого стоит проверять, что округленное totalAmount % 100 между 11 и 19 включительно находится

}
}

//получить последнюю цифру из числа для определения падежа слова рубль
private int GetLastIntDigit (double totalAmount) {
int intTotalAmount = (int) totalAmount;
String stringTotalAmount = String.valueOf(intTotalAmount);
int length = stringTotalAmount.length();
char lastDigit = stringTotalAmount.charAt(length-1);
Copy link

@MagicUnderHood MagicUnderHood Dec 10, 2022

Choose a reason for hiding this comment

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

Можно использовать деление по модулю - %10 для определения последней цифры

return Character.getNumericValue(lastDigit);
}
}

AltStyle によって変換されたページ (->オリジナル) /