-
Notifications
You must be signed in to change notification settings - Fork 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 |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import java.util.ArrayList; | ||
| public class Calculator { | ||
| ArrayList<Float> prices = new ArrayList<>(); | ||
| Formatter rub = new Formatter(); | ||
| public void addPrice(float price){ | ||
| prices.add(price); | ||
| } | ||
| public void samib() { | ||
| float sum = 0; | ||
| for(Float price : prices) { | ||
| sum += price; | ||
| } | ||
| int result2; | ||
| result2 = (int)Math.floor(sum / Main.quantity); | ||
| float result = sum / Main.quantity; | ||
| rub.formatRub(result2); | ||
| String format = "С каждого по %.2f %s"; | ||
| System.out.println(String.format(format, result, Formatter.padezh)); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| public class Formatter { | ||
| public static String padezh; | ||
|
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. Вместо использования переменной padezh лучше получать отформатированную строку через метод formatRub (поскольку метод уже возвращает строку). Это позволит избавиться от лишней переменной и уменьшит сложность класса, так как логика форматирования будет инкапсулирована в соответствующем методе. |
||
| public String formatRub(int result2) { | ||
| int x = result2 % 10; | ||
| int y = result2 % 100; | ||
| if(x == 0 || (x >= 5 && x <= 9) || (y>= 11 && y <= 14)){ | ||
| padezh = "рублей"; | ||
| }else if (x == 1 ) { | ||
| padezh = "рубль"; | ||
| }else { | ||
| padezh = "рубля"; | ||
| } | ||
|
Comment on lines
+6
to
+12
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. Условие Но еще лучше будет попробовать переписать эти условия на switch ... case |
||
| return padezh; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,58 @@ | ||
|
|
||
| import java.util.Scanner; | ||
| public class Main { | ||
|
|
||
| public static int quantity; | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| Products products = new Products(); | ||
| Calculator prices = new Calculator(); | ||
| String product; | ||
| float price; | ||
|
|
||
| while (true) { | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
| if(scanner.hasNextInt()){ | ||
| quantity = scanner.nextInt(); | ||
| scanner.nextLine(); | ||
| if (quantity > 1 ) { | ||
| break; | ||
| } else { | ||
| System.out.println("Введите значение больше 1"); | ||
| } | ||
| } else { | ||
| System.out.println("Введите целое число"); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
|
|
||
| String end = ""; | ||
| while (!end.equalsIgnoreCase("Завершить")) { | ||
| System.out.println("Введите название блюда"); | ||
| product = scanner.nextLine(); | ||
| products.addProduct(product); | ||
| while (true) { | ||
| System.out.println("Введите цену блюда"); | ||
| if (scanner.hasNextFloat() ) { | ||
| price = scanner.nextFloat(); | ||
| scanner.nextLine(); | ||
| if(price > 0) { | ||
| prices.addPrice(price); | ||
| break; | ||
| } else { | ||
| System.out.println("Введите цену больше 0"); | ||
| } | ||
| } else { | ||
| System.out.println("введите цифровое значение"); | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| System.out.println("Товар успешно добавлен"); | ||
| System.out.println("Добавить новый товар или завершить?"); | ||
| end = scanner.nextLine(); | ||
| } | ||
| System.out.println("Добавленные товары:"); | ||
| products.outputProducts(); | ||
| prices.samib(); | ||
| scanner.close(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import java.util.ArrayList; | ||
| public class Products { | ||
| ArrayList<String> products = new ArrayList<>(); | ||
|
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. Было бы лучше создать отдельный класс Product, содержащий следующие поля:
Таким образом, вместо списка строк мы будем использовать список объектов класса Product. Это также позволит избавиться от необходимости хранить отдельный список prices в классе Calculator. |
||
| public void addProduct(String product){ | ||
| products.add(product); | ||
| } | ||
| public void outputProducts() { | ||
| for(String product : products) { | ||
| System.out.println(product); | ||
| } | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.
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.
Предлагаю передавать количество quantity в качестве дополнительного параметра в функцию samib. Такой подход делает класс Calculator более независимым от класса Main, что повышает его переиспользуемость.
Также лучше перенести логику округления в функцию класса Formatter, поскольку он отвечает за форматирование данных и их представление.