-
Notifications
You must be signed in to change notification settings - Fork 222
Calculator #101
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: master
Are you sure you want to change the base?
Calculator #101
Changes from all commits
5559530
37d12f7
ccbe256
4f90a7b
c217e65
57deb09
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Calculator { | ||
|
|
||
| static Scanner scanner = new Scanner(System.in); | ||
| static String userInput = null; | ||
| static String productName; | ||
| static String allProductsList = "Добавленные товары:"; | ||
| static float productCost = 0.0F; | ||
| static float allProductsCost = 0.0F; | ||
| static float personalAmount = 0.0F; | ||
| static String checkedNumber = null; | ||
|
|
||
| static void printResult(int numberOfGuests) { | ||
| while (!"ЗАВЕРШИТЬ".equalsIgnoreCase(userInput)) {// цикл продолжается до ввода слова "заврешить" игнорируя регистр букв | ||
| System.out.println("Введите название товара и его цену.\nТовар: "); | ||
| productName = scanner.next(); | ||
| allProductsList = allProductsList + "\n" + productName; | ||
| System.out.println("Введите стоимость: "); | ||
| checkedNumber = scanner.next(); | ||
|
|
||
| while (true) {// цикл проверяет число ли ввёл пользователь и не является ли оно отрицательным | ||
| if (!isItaNumber(checkedNumber)) { | ||
| System.out.println("Бип, ошибка. Это не число, либо вы в качестве делителя используете запятую вместо точки.\nПопробуйте ещё раз. Введите цену: "); | ||
| checkedNumber = scanner.next(); | ||
| } else if (!isItPositive(productCost = Float.parseFloat(checkedNumber))) { | ||
| System.out.println("Бип, ошибка. Цена не может быть отрицательной!\nПопробуйте ещё раз. Введите цену: "); | ||
| checkedNumber = scanner.next(); | ||
| } else { | ||
|
|
||
| break; | ||
| } | ||
| } | ||
|
|
||
| allProductsCost += productCost; | ||
| System.out.println("Вы успешно добавили " + productName + " за " + String.format("%.2f", productCost) + " рублей.\nЕсли хотите завершить, наберите \"Завершить\" и нажмите \"enter\".\nЕсли хотите добавить ещё один товар, введите любой символ или слово и нажмите \"enter\"."); | ||
| userInput = scanner.next(); | ||
| } | ||
| String rubleEnding = getRubleEnding((int) Math.floor(allProductsCost)); // выясняем верное окончание слова "рубль" для общей суммы заказа | ||
| System.out.println(allProductsList + "\nОбщая сумма: " + String.format("%.2f", allProductsCost) + rubleEnding); | ||
| personalAmount = allProductsCost / numberOfGuests; | ||
| String personalRubleEnding = getRubleEnding((int) Math.floor(personalAmount));// выясняем верное окончание слова "рубль" для суммы отдельного гостя | ||
| System.out.println("Каждому гостю необходимо заплатить: " + String.format("%.2f", personalAmount) + personalRubleEnding); | ||
|
|
||
| } | ||
|
|
||
|
|
||
| private static boolean isItPositive(float productCost) {// проверяем не является ли число отрицательным | ||
| return productCost >= 0; | ||
| } | ||
|
|
||
| private static boolean isItaNumber(String checkedNumber) {// проверяем число ли ввёл пользователь | ||
|
|
||
| return checkedNumber.matches("-?\\d+(\\.\\d+)?"); | ||
| } | ||
|
|
||
| public static String getRubleEnding(int wholeRubles) {// подбираем правльное окончание слову "рубль" | ||
| int preLastDigit = wholeRubles % 100 / 10; | ||
| if (preLastDigit == 1) { | ||
| return " рублей."; | ||
| } else { | ||
|
|
||
| switch (wholeRubles % 10) { | ||
| case 1: | ||
| return " рубль."; | ||
| case 2: | ||
| case 3: | ||
| case 4: | ||
| return " рубля."; | ||
| default: | ||
| return " рублей."; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,27 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
| System.out.println("Привет Мир"); | ||
|
|
||
| int numberOfGuests = getNumberOfGuests(); | ||
| Calculator.printResult(numberOfGuests); | ||
|
|
||
| } | ||
|
|
||
| static int getNumberOfGuests() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| while (true) { | ||
| System.out.println("Введите количество гостей."); | ||
| int number = scanner.nextInt(); | ||
|
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. Пользователь может ввести на вопрос про количество человек вместо целого числа строку, и приложение упадет. Для стоимости товаров ты обрабатываешь такую ситуацию, стоит добавить обработку и для количества людей, чтобы приложение не падало/ Можешь использовать try-catch или hasNextInt |
||
| if (number == 1) { | ||
| System.out.println("Количество гостей дожно быть не менее 2-х человек. Найдите кого-нибудь, с кем можно разделить счёт."); | ||
| } else if (number < 2) { | ||
| System.out.println("Количество гостей не может быть меньше 1. Вероятно вы ошиблись."); | ||
| } else { | ||
| return number; | ||
| } | ||
|
|
||
| } | ||
| } | ||
| } | ||
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.
Все поля и методы класса лучше делать не статическими (убрать static у всех), в этом нет необходимости. А при вызове метода в Main создавать объект класса: