-
Notifications
You must be signed in to change notification settings - Fork 0
Первая версия проектной работы №1 - Консольное приложение "Калькулято… #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
base: dev
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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); | ||
| } | ||
| } |
| 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"); | ||
| } | ||
| } | ||
|
|
| 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)) { | ||
| System.out.print("\nНекорректное число! Количество человек должно быть целым, положительным числом! Попробуйте ещё раз: "); | ||
| input = scanner.next(); | ||
| } | ||
| persons = Integer.parseInt(input); | ||
|
|
||
| Bill bill = new Bill(); | ||
| String completion = ""; | ||
| while (completion.compareToIgnoreCase("Завершить") != 0) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно просто |
||
| System.out.print("\nВведите название товара: "); | ||
| bill.addToList(scanner.next()); | ||
| System.out.print("Введите стоимость товара: "); | ||
| input = scanner.next(); | ||
| while (!isValidDouble(input)) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. По аналогии с int у |
||
| 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; | ||
| } | ||
| } | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
У
Scannerесть удобный методhasNextInt, можно сразу узнать без дополнительных проверок возможно ли интерпретировать строку какint