-
Notifications
You must be signed in to change notification settings - Fork 0
Практическая работа из второго спринта v1.0. #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?
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 |
|---|---|---|
| @@ -1 +1 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # Проект был создан в 2023 году. На нем я практиковался писать код на Java |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import java.util.Scanner; | ||
| public class Calculator { | ||
| static double sum = 0.0; | ||
|
|
||
| // Добавление товаров в список | ||
| static void goodsInput() { | ||
| Scanner sc = new Scanner(System.in); | ||
|
|
||
| while (true) { | ||
|
|
||
| System.out.println("Введите название товара."); | ||
| String name = sc.next(); // ? | ||
|
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. Используя функцию scanner.nextLine() вместо scanner.next(), ты сможешь считывать не только одно слово, но и целые предложения в названии продукта.
Owner
Author
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. Изначально именно ее и использовал, если здесь заменить на .nextLine() строка перестанет считываться, не смог понять из-за чего это происходит. При этом с .next() все работает как надо. |
||
| double cost = 0.0; | ||
| while (true) { | ||
| System.out.println("Введите стоимость товара."); | ||
| if (sc.hasNextDouble()) { | ||
| cost = sc.nextDouble(); | ||
| if (cost > 0.0) { | ||
| sum += cost; | ||
| break; | ||
| } | ||
| } else { | ||
| System.out.println("ОШИБКА! Вы указали некорректное значение."); | ||
| sc.next(); | ||
| } | ||
| } | ||
|
|
||
| Goods.list = Goods.list + " " + name + " " + Double.toString(cost) + "\n"; | ||
|
|
||
| System.out.println("Товар успешно добавлен!"); | ||
| System.out.println("Хотите ввести следующий товар или завершить?"); | ||
| if (end()) { | ||
| break; | ||
| } | ||
| } | ||
| sc.close(); | ||
| System.out.println("Добавленные товары:"); | ||
| System.out.print(Goods.list); | ||
| System.out.println("==================="); | ||
| sc.close(); | ||
| } | ||
|
|
||
| // Расчет итоговой суммы | ||
|
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 void totalAmount(int people) { | ||
|
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 /= people; | ||
| System.out.println("Итоговая сумма: " + Formatter.rounding(sum) + " " + Formatter.rubles(sum) + "."); | ||
| } | ||
|
|
||
| // Обрабатываем случай, если вводят слово ЗАВЕРШИТЬ. | ||
| static boolean end() { | ||
| Scanner sc = new Scanner(System.in); | ||
|
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. после использования сканера хорошей практикой будет закрыть его с помощью функции scanner.close(), это позволит избежать возможных утечек памяти
Owner
Author
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. Да, это я знаю и в некоторых местах можно найти применения метода .close(). В тех местах, где его в конечном итоге не поставил, IDE подчеркивала строчку "sc.close()" красным. Если есть объяснения для такого явления, буду рад их услышать. |
||
| String input = sc.nextLine(); | ||
| if (input.equalsIgnoreCase("завершить")) { | ||
| return true; | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
|
|
||
| public class Formatter { | ||
|
|
||
| // Метод получения слова рубль в правильном падеже | ||
| static String rubles(double sum) { | ||
| if ((11 <= ((int)sum) % 100 ) && (((int)sum) % 100 <= 20)) { | ||
| return "рублей"; | ||
| } else { | ||
| switch (((int)sum) % 10) { | ||
| case 1: | ||
| return "рубль"; | ||
| case 2: | ||
| return "рубля"; | ||
| case 3: | ||
| return "рубля"; | ||
| case 4: | ||
| return "рубля"; | ||
| default: | ||
| return "рублей"; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Метод для округления | ||
| static String rounding(double num) { | ||
| return String.format("%.2f", num); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| public class Goods { | ||
| static String list = ""; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,29 @@ | ||
|
|
||
| import java.util.Scanner; | ||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| int people = peopleNumberInput(); | ||
| Calculator.goodsInput(); | ||
| Calculator.totalAmount(people); | ||
| } | ||
| public static int peopleNumberInput() { | ||
| Scanner sc = new Scanner(System.in); | ||
| int peopleNumber; | ||
|
|
||
| while (true) { | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
| if (sc.hasNextInt()) { | ||
| peopleNumber = sc.nextInt(); | ||
| if (peopleNumber > 1) { | ||
| return (peopleNumber); | ||
| } else { | ||
| System.out.println("ОШИБКА! Вы указали некорректное значение."); | ||
| } | ||
| } else { | ||
| System.out.println("Ошибка! Вы указали некорректное значение."); | ||
| sc.next(); | ||
| } | ||
| } | ||
| sc.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.
Всегда старайся выбирать понятные названия для переменных и констант. Хорошие названия выполняют роль документации и значительно облегчают процесс чтения кода.