-
Notifications
You must be signed in to change notification settings - Fork 222
Пишем консольное приложение #118
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?
Changes from all commits
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,20 @@ | ||
| public class CaseEnding { | ||
|
|
||
| static String roubleCase = " рублей"; | ||
| static double remainder; | ||
|
|
||
| static String setEnding(double price) { | ||
| if (Math.floor(price) >= 11 && Math.floor(price) <= 14) { | ||
|
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. Если здесь добавить деление по модулю на 100 |
||
| return roubleCase = " рублей"; | ||
| } else { | ||
| remainder = Math.floor(price) % 10; | ||
|
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.
|
||
| if (remainder == 1) { | ||
| return roubleCase = " рубль"; | ||
| } else if (remainder >= 2 && remainder <= 4) { | ||
| return roubleCase = " рубля"; | ||
| } else { | ||
| return roubleCase = " рублей"; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Item { | ||
|
|
||
| static String name; | ||
|
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. Все модификаторы static можно в этом классе убрать, а при вызове метода calculate в Main сначала создавать объект класса Item. Подробнее про static будет в следующих уроках, пока в нем сильной необходимости нет |
||
| static double price = 0; | ||
|
|
||
| static String values = ""; | ||
| static double sum = 0; | ||
|
|
||
| static void calculate() { | ||
|
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. Можно результатом этого метода возвращать посчитанную sum, тогда не надо будет её использовать в Main, код будет выглядеть логичнее |
||
| while (true) { | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| System.out.println("\nЕсли вы хотите добавить блюдо в калькулятор, введите наименование блюда:"); | ||
| System.out.println("Если вы не хотите добавлять блюдо в калькулятор, введите «Завершить»:"); | ||
|
|
||
| name = scanner.nextLine(); | ||
|
|
||
| if (name.equalsIgnoreCase("завершить")) { | ||
| System.out.println("Выход из калькулятора (вы ввели «Завершить»)."); | ||
| break; | ||
| } else { | ||
| System.out.println("Введите стоимость блюда в формате [рубли.копейки]:"); | ||
|
|
||
| String stringPrice = scanner.nextLine(); | ||
|
|
||
| try { | ||
| price = Double.parseDouble(stringPrice); | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Введите численное значение."); | ||
| price = 0; | ||
| } | ||
|
|
||
| if (price > 0) { | ||
| values += name + " " + price + ";\n"; | ||
| sum += price; | ||
|
|
||
| System.out.println("Блюдо " + name + " стоимостью " + price + CaseEnding.setEnding(price) + " успешно добавлено!"); | ||
| System.out.println("Текущая сумма блюд: " + sum + CaseEnding.setEnding(sum) + "."); | ||
| } else { | ||
| System.out.println("Введите корректную стоимость блюда больше нуля."); | ||
|
|
||
| } | ||
| } | ||
| } | ||
|
|
||
| System.out.println("\nДобавленные блюда: "); | ||
| System.out.println(values); | ||
| System.out.println("Общая сумма блюд: " + sum + CaseEnding.setEnding(sum) + "."); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,47 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
| System.out.println("Привет Мир"); | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| while (true) { | ||
|
|
||
| printMenu(); | ||
|
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. Можно этот вывод вынести до while, тогда он будет печататься один раз, в принципе этого достаточно для пользователя |
||
|
|
||
| String quantityOfPersons = scanner.nextLine(); | ||
| int number = -1; | ||
|
|
||
| try { | ||
| number = Integer.parseInt(quantityOfPersons); | ||
| } catch (NumberFormatException e) { | ||
| System.out.println("Вы ввели что-то не то... Давайте ещё раз."); | ||
| } | ||
|
|
||
| if (number == 1) { | ||
| System.out.println("Тебе грустно и одиноко, нечем заняться? Занимайся Джаббой!"); | ||
| } else if (number > 1) { | ||
| System.out.println("Итак, вас " + quantityOfPersons + ". И вы харчевали..."); | ||
| Item.calculate(); | ||
| double pricePerPerson = Item.sum / number; | ||
| System.out.println("\nКаждый из посетителей должен заплатить " + String.format("%.2f", pricePerPerson) + CaseEnding.setEnding(pricePerPerson) + "."); | ||
| System.out.println("Вычисления завершены. Выход."); | ||
| break; | ||
| } else if (number == 0) { | ||
| System.out.println("Выход, потому что кое-кто нажал ноль."); | ||
| break; | ||
| } else { | ||
| System.out.println("Введите положительное число гостей."); | ||
| } | ||
|
|
||
| } | ||
| } | ||
|
|
||
| public static void printMenu() { | ||
| System.out.println("\nДобрый день!"); | ||
| System.out.println("На скольких человек вы хотите разделить счёт?"); | ||
| System.out.println("Пожалуйста, введите количество гостей - от 1 и выше."); | ||
| System.out.println("Или введите 0 для того, чтобы выйти из программы."); | ||
| } | ||
| } | ||
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.
Переменную можно убрать, и ниже при возврате результата писать просто
return " <нужное слово>";. Или оставить переменную, но убрать здесь инициализацию, в каждом if убрать return, оставить только присваивание переменной нужного слова, а после всех if-else поставитьreturn roubleCase;