Skip to content

Практикум. Sprint 2. Консольное приложение 1. Алиев Анар. - #1

Open
darkelf007 wants to merge 13 commits into
mainfrom
dev
Open

darkelf007 wants to merge 13 commits into
mainfrom
dev

Conversation

@darkelf007

Copy link
Copy Markdown
Owner

Консольное приложение запись клиентов, калькулятор продуктов.

System.out.println("Введите наименоване товара (или 'Звершить' для завершения)");



Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Общепринято не оставлять так много пустых строк, это ухудшает восприятие. Золотой стандарт - 1 пустая строка, если надо отделить код

Comment thread src/main/java/Calculator.java Outdated
System.out.println("Введите положительное число");
continue;

} else if(priceNum>0){

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь if(priceNum>0) избыточен, так как если число не попало в if (priceNum <= 0), то оно сто процентов больше ноля

Comment thread src/main/java/Calculator.java Outdated
String format = "%.2f";

ArrayList<String> products = new ArrayList<>();
ArrayList<String> prices = new ArrayList<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему бы сразу не хранить цену в float? тем более что при чтение она переводится в этот тип. Так можно избежать еще одной конвертации при выводе товаров

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А возникла такая проблема, при вводе в консоли дробного числа, принимает только такой вид записи 11,11 а не 11.11 я нашел в стэк оверфло такой вариант был в начале объявляешь String а потом с помошью метода .parse... переводишь текст в число и при вводе в консоль принимает точку. так мне просто больше понравилось :D но если нужно я могу как вы просите объявить float и под него все подстроить?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Проблема точки и запятой в том, что в русской локали используется запятая, в английской точка. Решить можно тем, что вручную поставить в начале работы приложения локаль: Locale.setDefault(Locale.US); Тогда будет точка восприниматься, если поставить русскую, то запятая

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Извини, что только сейчас ответила, уведомлений с гита приходит много на почту, поэтому затерялось

Comment thread src/main/java/Calculator.java Outdated
System.out.println(" " + Ruble.getRuble(total));
System.out.println("");

Persons b = new Persons();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для переменных лучше использовать говорящие названия, использование a, b и тд настоятельно не рекомендуется, так как без контекста их не понять

Comment thread src/main/java/Calculator.java Outdated
double c = Double.parseDouble(b.countPersons());
double a = total / c;

System.out.print(String.format("Итого с каждого по: %.2f ", a));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно использовать System.out.printf("Товар: " + product + " Стоимость %.2f " , price2 ); чтобы избежать использование String.format. Метод printf умеет в форматирование по умолчанию

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

спасибо, теперь ИДИАЛЬНО :D

Comment thread src/main/java/Ruble.java Outdated

int correct = (int) Math.floor(rubles);
int count = correct%10;
if (count == 1){

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для таких случаев, когда несколько вариантов связанных, лучше использовать конструкцию switch-case. Это упрощает код визуально, позволяет уменьшить количество ошибок, так как становится нагляднее https://metanit.com/java/tutorial/2.5.php

Comment thread src/main/java/Calculator.java Outdated
import java.util.Scanner;

public class Calculator {
public void caclulator() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опечатка в название метода

Comment thread src/main/java/Calculator.java Outdated

while (true) {

System.out.println("Введите наименоване товара (или 'Звершить' для завершения)");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опечатка в Завершить

Comment thread src/main/java/Persons.java Outdated

if (number <= 1) {

System.out.println("Не корректоное значение для подсчета");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опечатка в некорректное

Comment thread src/main/java/Calculator.java Outdated
System.out.println(Ruble.getRuble(price2));
}

System.out.println("");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вместо System.out.println("") можно просто в предыдущем println добавлять символ новой строки в конец: \n

Comment thread src/main/java/Persons.java Outdated
while (true) {
persons = scanner.nextLine();
try {
Integer number = Integer.parseInt(persons);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь вместо Integer можно использовать тип int, так как это примитивное число, которое не может быть null. Это более выгодно для производительности, так как примитивные типы хранятся в стеке, это тип памяти, к которому есть быстрый доступ, где хранятся простые типы и ссылки на объекты в порядке добавления (первая запись снизу, последняя сверху). Integer в свою очередь - это объект, который хранится уже в так называемой куче (heap), в памяти, где занимает определенной количество памяти, к куче доступ более медленный.
https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/int-vs-Integer-java-difference-comparison-primitive-object-types https://habr.com/ru/articles/104231/

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

О спасибо!

Comment thread src/main/java/Ruble.java Outdated
Comment on lines +7 to +41
switch (count) {
case 1:
case 21:
case 31:
case 41:
case 51:
case 61:
case 71:
case 81:
case 91:
return "Рубль";

case 2:
case 22:
case 32:
case 42:
case 52:
case 62:
case 72:
case 82:
case 92:
case 3:
case 23:
case 33:
case 43:
case 53:
case 63:
case 73:
case 83:
case 93:
case 4:
case 24:
case 34:
case 44:
case 54:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы не было такого длинного case, можно сделать так: Посчитать остаток от деления на 100: %100, посчитать остаток от деления на 10: %10. Далее сначала проверить, что остаток от деления на сто находится в диапазоне 11-19, затем уже работать с остатком на 10: Проверить на 1, 2-4 и остальное рублей. Тогда миллион кейсов можно будет убрать)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А еще если использовать версию джавы повыше, то case'ы можно схлопывать: https://javarush.com/groups/posts/operator-switch-v-java

@Anna-Malinina

Copy link
Copy Markdown

image

@darkelf007
darkelf007 force-pushed the dev branch 2 times, most recently from 331401e to 214c843 Compare October 8, 2023 18:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants