-
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
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,87 @@ | ||
| import java.util.InputMismatchException; | ||
| import java.util.Scanner; | ||
| import java.util.ArrayList; | ||
|
|
||
| public class Calculator { | ||
|
|
||
| public static String calculator(int N) { | ||
|
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. старайся избегать использования статических функций, так как они не очищаются и всегда занимают место в памяти
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. Понял. Но вроде в курсе ещё не встречал эту информацию) |
||
|
|
||
| ArrayList<Product> products = new ArrayList<>(); | ||
| Scanner scanner = new Scanner(System.in); | ||
| double sum = 0; | ||
|
|
||
| while (true) { | ||
|
|
||
| System.out.println("Пожалуйста, введти название товара: "); | ||
| String productName = prod(scanner); | ||
|
|
||
| System.out.println("Пожалуйста, укажите в формате 'рубли,копейки' стоимость товара: "); | ||
| double priceProduct = prPr(scanner); | ||
| sum += priceProduct; | ||
|
|
||
| products.add(new Product(productName, priceProduct)); | ||
| System.out.println("Товар успешно добавлен"); | ||
|
|
||
| System.out.println("Будут ли ещё товары? Если нет, пожалуйста, введите 'Завершить'."); | ||
| String z = scanner.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. не сокращай имена переменных и не используй аббревиатуры, к коду приходится возвращаться время от времени и бывает сложно понять, что значит то или иное сокращение через месяц или два |
||
|
|
||
|
|
||
| if(z.equalsIgnoreCase("Завершить")) { | ||
|
|
||
| for (int i = 0; i < products.size(); i++) { | ||
| Product product = products.get(i); | ||
| System.out.println("Товар: " + product.productName + ", стоимость товара: " + product.priceProduct + "."); | ||
| } | ||
|
|
||
| double midSum = sum/N; | ||
|
|
||
| String form = String.format("%.2f", midSum); | ||
| String f = rub(midSum); | ||
| return form + f; // возвращаем средний чек на человека | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public static String prod (Scanner scanner) { | ||
| while (true) { | ||
| try { | ||
| String productName = scanner.next(); | ||
| return productName; | ||
| } catch (InputMismatchException q) { | ||
| System.out.println("Введено некорректно название товара."); | ||
| } finally { | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| } | ||
| public static double prPr (Scanner scanner) { | ||
| while (true) { | ||
| try { | ||
| double prPr = scanner.nextDouble(); | ||
| if (prPr <= 0) { | ||
| System.out.println("Введена отрицательная или нулевая стоимость товара. Повторите ввод, пожалуйста."); | ||
| } else { | ||
| return prPr; | ||
| } | ||
| } catch (InputMismatchException q) { | ||
| System.out.println("Введена некорректная стоимость товара."); | ||
| } finally { | ||
| scanner.nextLine(); | ||
| } | ||
| } | ||
| } | ||
| public static String rub(double midSum) { | ||
| double v = Math.floor(midSum); | ||
| if (v % 100 >= 11 && v % 100 <=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. для ситуаций когда 2 и более условия, почти всегда лучше использовать switch/case |
||
| return " рублей"; | ||
| } else if (v % 10 == 1) { | ||
| return " рубль"; | ||
| } else if (v % 10 == 2 || v % 10 == 3 || v % 10 == 4) { | ||
| return " рубля"; | ||
| }else { | ||
| return " рублей"; | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,37 @@ | ||
| import java.util.Scanner; | ||
| import java.util.InputMismatchException; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| int numberOfPeople = 0; // хранит ответ пользователя | ||
|
|
||
| while (true) { | ||
|
|
||
| try { | ||
| numberOfPeople = scanner.nextInt(); | ||
| } catch (InputMismatchException q) { | ||
|
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. с одной стороны, когда ты используешь более конкретный класc ошибки, то ты как бы делаешь свой код более точным, но с другой стороны, если произойдет любая другая ошибка, то твой код упадет и всё сломается, поэтому если на это нет острой необходимости, то проще использовать просто класс Exception
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. Вот тут я просто глядел форумы. Искал ответ, как лучше будет. Поэтому решил оставить так. Но я вас понял. Спасибо. |
||
| System.out.println("Введено не целое число."); | ||
| } finally { | ||
| scanner.nextLine(); | ||
| } | ||
|
|
||
| if (numberOfPeople == 1) { | ||
|
|
||
| System.out.println("В этом случае нет смысла ничего считать и делить."); | ||
|
|
||
| } else if (numberOfPeople < 1) { | ||
|
|
||
| System.out.println("Некорректное значение для подсчёта."); | ||
|
|
||
| } else if (numberOfPeople > 1) { | ||
|
|
||
| String s = Calculator.calculator(numberOfPeople); | ||
|
|
||
| System.out.println("Каждый заплатит: " + s + "."); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| public class Product { | ||
|
|
||
| String productName; | ||
| double priceProduct; | ||
|
|
||
| public Product (String productName, double priceProduct) { | ||
| this.productName = productName; | ||
| this.priceProduct = priceProduct; | ||
| } | ||
| } |