Repository navigation
калькулятор #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: main
Are you sure you want to change the base?
калькулятор #1
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,50 @@ | ||
| public class Calculator { | ||
|
|
||
| String tovar = ""; | ||
| double sum; | ||
|
|
||
|
|
||
| public void tovarName(String tovar, double cost) { | ||
|
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. Поплыло форматирование во всем файле. Есть хороший хоткей, можно нажать Alt + Ctrl + L и студия красиво отформатирует весь код на экране |
||
|
|
||
| if (cost < 1) { | ||
| System.out.println("Извините, товар не может столько стоить."); | ||
| } | ||
| else { | ||
| sum += cost; | ||
| this.tovar += tovar + ", "; | ||
| System.out.println("Отлично, товар добавлен в корзину."); | ||
| } | ||
| } | ||
| public void check(int howMany) { | ||
|
|
||
| System.out.println("Все добавленные товары:"); | ||
| System.out.println(this.tovar); | ||
|
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. Такие подряд идущие println можно объединить в один. |
||
| //this.tovar.substring(0, this.tovar.lenght() - 1); | ||
| System.out.println("Общая цена заказа: " + String.format("%.2f", sum)) ; | ||
| System.out.print("Каждый человек должен заплатить: " + String.format("%.2f", sum/howMany)) ; | ||
|
|
||
| } | ||
| public String price(int howMany) { | ||
| if ((int)((sum/howMany) % 100/10) == 1) { | ||
| return " рублей."; | ||
| } | ||
| return switch ((int) ((sum / howMany) % 10)) { | ||
| case 1 -> " рубль."; | ||
| case 2, 3, 4 -> " рубля."; | ||
| default -> " рублей."; | ||
| }; | ||
| } | ||
| //public String removeLastChar(String tovar) { | ||
| // tovar = this.tovar; | ||
| // if (tovar != null) { | ||
| // tovar.substring(0, tovar.length() - 2); | ||
| // this.tovar = tovar; | ||
| // return this.tovar; | ||
| // } | ||
| // else { | ||
| // return this.tovar; | ||
| // } | ||
| //} | ||
|
|
||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,51 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
| int howMany; | ||
| System.out.println("На сколько человек необходимо разделить счёт?"); | ||
|
|
||
| while (true) { | ||
| if (!scanner.hasNextInt()) { | ||
| System.out.println("Простите, возникла ошибка, не могли бы вы ввести число. На скольких человек необходимо разделить счёт?"); | ||
| scanner.next(); | ||
| } else if (scanner.nextInt() <= 1) { | ||
| System.out.println("Простите, возникла ошибка, не могли бы повторить ввод. На скольких человек необходимо разделить счёт?"); | ||
| } else { | ||
| System.out.println("Подтвердите количество человек, это нужно для корректного рассчёта"); | ||
| howMany = scanner.nextInt(); | ||
| System.out.println("Отлично, счет будет поделен на " + howMany + " человек"); | ||
| break; | ||
| } | ||
|
|
||
| } | ||
|
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. Такие отдельные логические блоки, как этот (ввод и обработка количества людей), а также логические блоки с вводом товаров и выводом результатов лучше выносить в отдельные методы и затем вызывать их там, где необходимо. Это позволяет улучшить читаемость кода, т.к. разнородная логика не смешивается в один сплошной код, а также упрощает поддержку кода. |
||
|
|
||
| Calculator calculator = new Calculator(); | ||
|
|
||
| while (true) { | ||
| scanner.nextLine(); | ||
| System.out.println("Пожалуйста, введите название товара"); | ||
| String tovar = scanner.nextLine(); | ||
| System.out.println("Пожалуйста, введите стоимость товара в формате \"рубли,копейки\""); | ||
| if (scanner.hasNextDouble()) { | ||
| double cost = scanner.nextDouble(); | ||
| calculator.tovarName(tovar, cost); | ||
| System.out.println("Если желаете заказать что-то ещё, напишите любой символ. \n" + "Если желаете закончить заказ, напишите \"Завершить\"."); | ||
| } | ||
| else { | ||
| System.out.println("Введено некорректное значение цены товара, пожалуйста, повторите заказ."); | ||
| } | ||
| String nextVvod = scanner.next(); | ||
| if (nextVvod.equalsIgnoreCase("Завершить")) { | ||
| //String tovar1 = ""; | ||
| // calculator.removeLastChar(tovar1); | ||
| calculator.check(howMany); | ||
| System.out.println(calculator.price(howMany)); | ||
| break; | ||
| } | ||
| } | ||
| scanner.close(); | ||
| } | ||
| } | ||
| } | ||
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.
private