-
Notifications
You must be signed in to change notification settings - Fork 0
Проектная работа No1 #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 |
|---|---|---|
| @@ -1,22 +1,105 @@ | ||
| class Calculator { | ||
| import java.io.IOException; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Scanner; | ||
|
|
||
| int friendsCount; | ||
| public class Calculator { | ||
|
|
||
| String cart = "Добавленные товары:"; | ||
| double totalPrice = 0; | ||
| private int humanCount; | ||
|
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. Студия подсказывает, что переменную можно перенести в конструктор, где она инициализируется, быть полем класса ей не обязательно |
||
| private static final Scanner scanner = new Scanner(System.in); | ||
| private List<Product> productsList; | ||
|
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. Переменная инициализируется, но не используется |
||
| private static double priceAllProducts = 0; | ||
|
|
||
| public Calculator(){ | ||
| humanCount = divideBuild(); | ||
| this.productsList = addProducts(humanCount); | ||
|
|
||
| Calculator(int friendsCount) { | ||
| this.friendsCount = friendsCount; | ||
| } | ||
|
|
||
| void addItem(Item item) { | ||
| totalPrice += item.price; | ||
| cart = cart + "\n" + item.name; | ||
| public static int divideBuild(){ | ||
| while (true){ | ||
| try{ | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
| int count = Integer.parseInt(scanner.nextLine()); | ||
|
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. Можешь применить в студии автоформатирование (в выбранном файле, сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L), тогда автоматически код выправится |
||
| if(count < 1){ | ||
| System.out.println("Ошибка. Введено некорректное значение для подсчёта. Попробуйте снова"); | ||
| } | ||
| else if(count == 1){ | ||
| System.out.println("Нет смысла ничего считать и делить. Попробуйте снова"); | ||
| } | ||
| else { | ||
| return count; | ||
| }}catch (Exception e){ | ||
| System.out.println("Ошибка. Попробуйте снова."); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| System.out.println(item.name + " в корзине"); | ||
| public static List<Product> addProducts(int humanCount){ | ||
| List<Product> list = new ArrayList<>(); | ||
| while(true){ | ||
| System.out.println("Введите название одного товара или слово \"Завершить\" для подсчета стоимости"); | ||
| String product = scanner.nextLine(); | ||
| if(product.equalsIgnoreCase("Завершить")){ | ||
| if(list.size() == 0){ | ||
| System.out.println("Товар не был введен, программа завершена."); | ||
| } | ||
| else { | ||
| System.out.println("Добавленные товары:"); | ||
| for(Product products : list){ | ||
| System.out.println(products.getName()); | ||
| } | ||
| double pay = priceAllProducts / humanCount; | ||
| //double pay2 = Math.floor(pay); | ||
| String payformat = String.format("%.2f", pay); | ||
| String rub = floor(pay); | ||
| System.out.println("Каждый человек из " + humanCount +" должен заплатить " + payformat + " " + rub); | ||
| } | ||
| break;} | ||
| System.out.println("Введите стоимость товара в формате: 'рубли.копейки'"); | ||
| try{ | ||
| String price0 = scanner.nextLine(); | ||
| Double price = Double.parseDouble(price0); | ||
| priceAllProducts += price; | ||
| list.add(new Product(product,price));} | ||
| catch (NumberFormatException e){ | ||
| System.out.println("Задан неверный формат стоимости, начните заново"); | ||
| } | ||
| } | ||
| return list; | ||
| } | ||
|
|
||
| double divideSum() { | ||
| return totalPrice / friendsCount; | ||
| private static String floor(double pay){ | ||
| String rub = Integer.toString((int)Math.floor(pay)); | ||
| if(rub.length() == 1){ | ||
| switch (rub) { | ||
| case "0": | ||
| case "5": | ||
| case "6": | ||
| case "7": | ||
| case "8": | ||
| case "9": | ||
| return "рублей"; | ||
|
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. Можно все эти варианты оставить на последнюю ветку default |
||
| case "1": | ||
| return "рубль"; | ||
| case "2": | ||
| case "3": | ||
| case "4": | ||
| return "рубля"; | ||
| } | ||
| } | ||
| else if(rub.length() > 1){ | ||
|
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. Проверку можно упростить, если использовать |
||
| int lastDigit = Integer.parseInt(Character.toString(rub.charAt(rub.length()-1))); | ||
| if(rub.length() == 2 && rub.charAt(0) == '1'){return "рублей!!";} | ||
| else if(lastDigit >= 5 && lastDigit <= 9 ) | ||
| return "рублей"; | ||
| else if(lastDigit >= 2 && lastDigit <= 4 ) | ||
| return "рубля"; | ||
| else if(lastDigit == 1) | ||
| return "рубль"; | ||
| else | ||
| return "рублей"; | ||
| } | ||
| return "Ошибка"; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,9 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| int friendCount; | ||
| while (true) { | ||
| System.out.println("На сколько человек необходимо разделить счет?"); | ||
| friendCount = scanner.nextInt(); | ||
|
|
||
| if (friendCount > 1) { | ||
| break; | ||
| } else if (friendCount == 1) { | ||
| System.out.println( | ||
| "Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы."); | ||
| } else { | ||
| System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз."); | ||
| } | ||
| } | ||
|
|
||
| Calculator calculator = new Calculator(friendCount); | ||
|
|
||
| while (true) { | ||
| System.out.println("Введите название товара"); | ||
| String name = scanner.next(); | ||
|
|
||
| System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]"); | ||
| double price = scanner.nextDouble(); | ||
|
|
||
| calculator.addItem(new Item(name, price)); | ||
|
|
||
| System.out.println( | ||
| "Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления"); | ||
| String answer = scanner.next(); | ||
|
|
||
| if (answer.equalsIgnoreCase("Завершить")) { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| double result = calculator.divideSum(); | ||
| Formatter formatter = new Formatter(); | ||
| Calculator calculator = new Calculator(); | ||
|
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. Переменная не используется. Можно методы divideBuild и addProducts вызывать отсюда, чтобы выполнение программы было более прозрачным, а не в конструкторе |
||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
|
|
||
| System.out.println(calculator.cart); | ||
| System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result)); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| public class Product{ | ||
| private String name; | ||
| private double price; | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public double getPrice() { | ||
| return price; | ||
| } | ||
|
|
||
| public Product(String name, double price){ | ||
| this.name = name; | ||
| this.price = price; | ||
| } | ||
|
|
||
| } |