Repository navigation
Выполненная проектная работа №1 #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
9b8a0cf
88d05a8
ba94dc3
131a092
2c1c71d
75f566a
62dfdce
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,17 @@ | ||
| import java.util.HashMap; | ||
|
|
||
| public class Calculator { | ||
|
|
||
| public static double sumPrice(HashMap <String, Double> productsMap){ | ||
| double sumPriceResult = 0.00f; | ||
| for (String i: productsMap.keySet()) { | ||
| sumPriceResult = sumPriceResult + productsMap.get(i); | ||
| } | ||
| return sumPriceResult; | ||
| } | ||
|
|
||
| public static double priceForPerson(HashMap <String, Double> productsMap,int humans){ | ||
| return sumPrice(productsMap) / humans; | ||
| } | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import static java.lang.Math.floor; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
|
|
||
| public class Formatter { | ||
| String Formatter(double price) { | ||
| int modPrice = (int) (floor(price)); | ||
| //это хотфикс, потом понял, где неправильно | ||
| // и в итоге не смог быстро всё пофиксить по нормальному | ||
| if (modPrice % 100 > 11 && modPrice % 100 < 15) | ||
| modPrice = modPrice % 100; | ||
| else if (modPrice > 11 && modPrice < 15) | ||
| return "рублей"; | ||
| else | ||
| modPrice = modPrice % 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. Все приходит с опытом) Потом привыкнешь и уже будет у самого глаза болеть от кривого форматирования)) |
||
| return switch (modPrice) { | ||
| case 1 -> "рубль"; | ||
| case 2 -> "рубля"; | ||
| case 3 -> "рубля"; | ||
| case 4 -> "рубля"; | ||
| default -> "рублей"; | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,41 @@ | ||
| /* | ||
| Programm designed our devops | ||
| I'm so sorry | ||
|
|
||
| ## | ||
| ## Calculator vashego nastorenia version 0.4 | ||
| ## | ||
| */ | ||
|
|
||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static final String ANSI_YELLOW = "\u001B[33m"; | ||
| public static final String ANSI_RESET = "\u001B[0m"; | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| int humans = 0; | ||
|
|
||
| while (humans <= 1) { | ||
| System.out.print("\nВведите количество гостей "); | ||
| try { | ||
|
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. |
||
| humans = scanner.nextInt(); | ||
| if (humans <= 1) { | ||
| System.out.println(ANSI_YELLOW + | ||
| "Счёт не делится на такое количество человек." + | ||
| "\nВведите корректное число людей!(больше 1)" + ANSI_RESET); | ||
| } | ||
| } catch (Exception e) { | ||
| System.err.println("Ёкарный бабай, шнурок, целое число больше одного введи"); | ||
| // Как понял из описаний в интернетах, из-за того, что первый раз мы вводим неправильный | ||
|
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. Я тоже так поняла)) |
||
| // символ и в сканнере он остаётся, мы не успеваем сменить символ и входим в эксепшн, | ||
| // эксепшн ловит ошибку и снова убегает в catch, из-за этого цикл бесконечный, | ||
| // а это мы задаём пустой символ и тогда значение в сканнере обнуляется. | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| Product.products(humans); | ||
|
|
||
| System.out.println("Спасибо, что воспользовались нашей программой"); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import java.util.HashMap; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Product { | ||
| public static final String ANSI_YELLOW = "\u001B[33m"; | ||
| public static final String ANSI_RESET = "\u001B[0m"; | ||
| public static void products(int humans) { | ||
| Scanner scanner = new Scanner(System.in); | ||
| double productPrice = 0.00f; | ||
| HashMap<String, Double> productsMap = new HashMap<String, Double>(); | ||
|
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 (true) { | ||
| System.out.print("Введите название продукта "); | ||
| String productName = scanner.next(); | ||
|
|
||
| System.out.print("Введите стоимоть продукта "); | ||
|
|
||
| try { | ||
| // вызывал конструктор parseDouble типа Double и перевожу строку в double | ||
| // Сам я не додумался, а за меня додумался интернет | ||
|
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. Это норма) Главное уметь искать и понимать, что ты нашел) |
||
| productPrice = Double.parseDouble(scanner.next().replace(",", ".")); | ||
| if (productPrice > 0) { | ||
| productsMap.put(productName, productPrice); | ||
| System.out.println("Товар успешно добавлен\n"); | ||
|
|
||
| System.out.print("Желаете добавить ещё товар?(Введите да, нет, завершить) \n"); | ||
| String wishQuestion = scanner.next(); | ||
|
|
||
| if (wishQuestion.equalsIgnoreCase("завершить") || | ||
| wishQuestion.equalsIgnoreCase("нет")) { | ||
| result(productsMap, humans); | ||
| break; | ||
| } | ||
| } else { | ||
| //Моя девушка сказала, раз эт неправильно, то почему оно не красится=) | ||
|
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. Ничесе, я такого варианта еще не встречала в этой работе)) Девушке респект |
||
| // пользователю, говорит, непонятно, ошибка это или нет | ||
| System.out.println(ANSI_YELLOW + "Ёкарный бабай, шнурок, " + | ||
| "когда последний раз за " + "твой кофе заправка платила?" + ANSI_RESET); | ||
| } | ||
| } catch (Exception e) { | ||
| System.err.println("Ёкарный бабай, мужики, как должно выглядеть число то?"); | ||
| } | ||
|
|
||
|
|
||
| } | ||
| } | ||
|
|
||
| private static void result(HashMap<String, Double> productsMap, int humans){ | ||
| Formatter formatter = new Formatter(); | ||
| double productsSum = Calculator.sumPrice(productsMap); | ||
|
|
||
| System.out.println("Добавленные товары:\n"); | ||
| for (String i : productsMap.keySet()) { | ||
| System.out.printf("Товар \"%s\" стоимостью \"%.2f\" %s\n", i, | ||
| productsMap.get(i), | ||
| formatter.Formatter(productsMap.get(i))); | ||
| } | ||
| System.out.printf("Полная сумма всех товаров %.2f %s \n", | ||
| Calculator.sumPrice(productsMap), | ||
| formatter.Formatter(productsSum)); | ||
| System.out.printf("Каждый посетитель должен заплатить %.2f %s \n", | ||
| Calculator.priceForPerson(productsMap, humans), | ||
| //Насколько правильно вызвать функцию, в которой вызывается функция? <------ | ||
|
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. Да в целом так делают) Если выражение не становится супер сложным и длинным |
||
| formatter.Formatter(Calculator.priceForPerson(productsMap, humans))); | ||
| } | ||
|
|
||
| } | ||

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.
Ну вообще можно было просто сохранить mod 10, mod 100, а потом в свитч кейсе сначала мод 100 проверить на 11-15, а потом мод 10 на все остальное