Repository navigation
Калькулятор блюд #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,55 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Objects; | ||
| import java.util.Scanner; | ||
|
|
||
| public class CalculateDishes { | ||
| private int countPeople; | ||
| private ArrayList<Dish> dishesArr = new ArrayList<>(); | ||
|
|
||
| public ArrayList<Dish> getDishesArr() { | ||
| return dishesArr; | ||
| } | ||
|
Comment on lines
+7
to
+11
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. Здорово, что написал аксессор для для массива, молодец! |
||
|
|
||
| public int getCountPeople() { | ||
| return this.countPeople; | ||
| } | ||
|
|
||
| public void setCountPeople(int countPeople) { | ||
| this.countPeople = countPeople; | ||
| } | ||
|
|
||
| public void addDish(Dish dish) { | ||
| this.dishesArr.add(dish); | ||
| } | ||
|
Comment on lines
+13
to
+23
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. Очень классно, что используешь ООП подход и хранишь состояние внутри класса и выставляешь только методы для работы с ним. Также здорово, что ты не используешь сканер внутри калькулятора, ввод должен быть отделён. Молодец! |
||
|
|
||
| public float getAmout(){ | ||
|
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. Опечатка, должно быть Amount nit |
||
| float amount =0.00f; | ||
| for (Dish dish: dishesArr){ | ||
| amount += (float) dish.getPrice(); | ||
| } | ||
| return amount; | ||
| } | ||
|
|
||
|
|
||
|
|
||
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) return true; | ||
| if (!(o instanceof CalculateDishes that)) return false; | ||
| return getCountPeople() == that.getCountPeople() && Objects.equals(getDishesArr(), that.getDishesArr()); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(getCountPeople(), getDishesArr()); | ||
| } | ||
|
Comment on lines
+35
to
+45
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. Нет ничего плохого в том, чтобы реализовать equals и hashCode, но кажется они нигде в коде дальше не используются и не очень понятно зачем они здесь. |
||
|
|
||
| @Override | ||
| public String toString() { | ||
| String messenger = "Добавленные товары:\n"; | ||
| for (Dish dish : this.dishesArr){ | ||
| messenger = messenger + dish.getName() +'\n'; | ||
| } | ||
| return messenger; | ||
| } | ||
| } | ||
|
Comment on lines
+47
to
+55
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. Можно было бы сделать отдельной функцией, не toString. toString скорее используется чтобы показать какое-то внутреннее состояние объекта, например, для логов. Здесь же мы хотим получить текст конкретного форматирования для показа пользователю. |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import java.util.Objects; | ||
|
|
||
| public class Dish { | ||
| private final String name; | ||
| private final double price; | ||
|
|
||
| public Dish(String name, double price) { | ||
| this.name = name; | ||
| this.price = price; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public double getPrice() { | ||
| return price; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object o) { | ||
| if (this == o) return true; | ||
| if (!(o instanceof Dish dish)) return false; | ||
| return Double.compare(getPrice(), dish.getPrice()) == 0 && Objects.equals(getName(), dish.getName()); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(getName(), getPrice()); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Dish{" + | ||
| "name='" + name + '\'' + | ||
| ", price=" + price + | ||
| '}'; | ||
| } | ||
| } | ||
|
Comment on lines
+21
to
+39
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. Опять же, нет ничего плохого в том чтобы реализовать эти методы, но кажется, что они нигде не используются в коде и не очень понятно для чего они тут. |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,64 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| CalculateDishes calc = new CalculateDishes(); | ||
| Scanner sc = new Scanner(System.in); | ||
| // System.out.println("Hello world!"); | ||
|
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 countPeople; | ||
| System.out.println("Введите число участников, на которых будет разделен счет:"); | ||
|
|
||
| while (true) { | ||
| if (sc.hasNextInt()) { | ||
| countPeople = sc.nextInt(); | ||
| if (countPeople <= 1) { | ||
| System.out.println("Количество людй не может быть менее 2\n" + | ||
| "Пожалуйста повторите ввод снова"); | ||
| } else { | ||
| break; | ||
| } | ||
| } else { | ||
| System.out.println("Вам необходмо ввести целое число\n" + | ||
| "Пожалуста повторите ввод снова"); | ||
| sc.next(); | ||
| } | ||
| } | ||
|
|
||
| calc.setCountPeople(countPeople); | ||
|
|
||
| System.out.println("Далее Вам необходимо ввести наименование блюда" + | ||
| "и его стоимость в формате рубли.копейки"); | ||
| String query = ""; | ||
| while (true) { | ||
| if (query.trim().replace("'", "").equalsIgnoreCase("завершить")) { | ||
|
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(calc.toString()); | ||
|
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. toString() здесь не обязательно вызывать, он будет вызван автоматически nit |
||
| printFormatRub.outFormattedRub(calc.getAmout() / calc.getCountPeople()); | ||
| break; | ||
| } else { | ||
| try { | ||
| System.out.println("Ведите наименование блюда:"); | ||
| String dishName = new Scanner(System.in).nextLine().trim(); | ||
|
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("Введите стоимость блюда:"); | ||
| double price = Double.parseDouble(new Scanner(System.in).next().trim()); | ||
| if (price <= 0 || dishName.isEmpty()) { | ||
| System.out.println("Некорректное значение, товар не был добавлен!"); | ||
| System.out.println("Повторите попытку ввода данных"); | ||
| } else { | ||
| calc.addDish(new Dish(dishName, price)); | ||
| System.out.println("Товар успешно добавлен!"); | ||
| System.out.println("Текущая сумма =" + calc.getAmout()); | ||
| System.out.println("Если вы закончить ввод блюд введите команду команду " + | ||
| "`завершить'\n" + | ||
| "В противном случае введите клавишу Enter"); | ||
|
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. Не очень понятно зачем добавлено дополнительное нажатие на клавишу энтер. Можно сделать без него. |
||
| query = new Scanner(System.in).nextLine(); | ||
| } | ||
| } catch (NumberFormatException e) { | ||
| System.out.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. Опечатка: НекорректнАЯ цена, блюдо не былО добавленО! nit |
||
| System.out.println("Повторите попытку ввода данных"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
|
|
||
| public class printFormatRub { | ||
|
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. Имена классов должны начинаться с большой буквы и писаться UpperCamelCase. И как я писал выше, лучше чтобы это было существительное. В данном случае можно назвать, например, RubFormatter. |
||
|
|
||
| public static void outFormattedRub(double num){ | ||
| int val= (int)num; | ||
| String s=""; | ||
| if (val>=5 && val%100<=20) s="рублей"; | ||
| else if (val%10==1) s="рубль"; | ||
| else if (new ArrayList<Integer>(Arrays.asList(2,3,4)).contains(val%10)) s="рубля"; | ||
| else s="рублей"; | ||
|
Comment on lines
+9
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 вместо каскадного if-else. Но алгоритм работает, молодец! |
||
| System.out.println(String.format("Каждый из друзей должен заплатить %.2f %s", num, s)); | ||
|
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. String.format() здесь лишний, println сам по себе работает как format. |
||
| } | ||
| } | ||
|
|
||
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.
Классы лучше называть существительными и функции глаголами. То есть, например, класс
DishCalculatorможет иметь методcalculate()