Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Comments

First project YP#22

Open
PavelRomashin wants to merge 3 commits intoYandex-Practicum:master from
PavelRomashin:master
Open

First project YP #22
PavelRomashin wants to merge 3 commits intoYandex-Practicum:master from
PavelRomashin:master

Conversation

@PavelRomashin
Copy link

@PavelRomashin PavelRomashin commented Aug 23, 2022

My first try at Java

while (true) { //Цикл ввода количества персон, на которое делится счет
System.out.println("На сколько человек нужно разделить счёт?\nВведите целым числом");
Scanner scanner = new Scanner(System.in); // Ввод числа людей
x = scanner.nextInt();// Запоминаем число
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Пользователь может не послушать рекомендацию "Введите целым числом" и ввести строку, тогда приложение упадет. Лучше такого не допускать, а обрабатывать. Можно использовать метод scanner.hasNextInt() или try-catch

// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");

int x;
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Это не очень информативное название для переменной, коллегам придётся вникать, для чего она используется. Лучше задать понятное имя, например, personCount

System.out.println("На сколько человек нужно разделить счёт?\nВведите целым числом");
Scanner scanner = new Scanner(System.in); // Ввод числа людей
x = scanner.nextInt();// Запоминаем число
System.out.println(x);//проверка 1 - вывод числа
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Такие отладочные выводы можно делать для себя, но при сдаче работы лучше их закомментировать, всё-таки в реальном приложении такие вещи пользователям попадать не должны

else {
System.out.println(String.format(message,sum/persons) + message3);
}
}
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Видно, что местами не хватает отступов или пробелов (в условиях выше, например), ты можешь применить в студии автоформатирование (в выбранном файле, сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L), тогда автоматически код выправится.

Chernou reacted with thumbs up emoji
if (sum1%10>=2||sum1%10<=4) {
System.out.println(String.format(message,sum/persons) + message2); // окончание"рубля"
}
else if (sum1%10 ==1){
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

sum1%10 повторяется несколько раз, можно вынести в переменную и сравнивать уже с ней

System.out.println("Введите название товара или напишите \"завершить\"");
Scanner scanner = new Scanner(System.in);// Ввод
String pos = scanner.next();//Считывание названия товара
if (pos.equalsIgnoreCase("завершить") == false) {// проверяем, что "не завершить"
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Условие можно заменить на !pos.equalsIgnoreCase("завершить"), это будет то же самое. ! - это "not" оператор

while (true) {
System.out.println("введите стоимость товара в формате рубли.копейки [10.45, 11.40]");
double price;//Считывание цены товара
price = scanner.nextDouble();
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Если ввести число в формате 10.45, приложение упадет. А вот ввод через запятую принимает. Можно разобраться, почему так происходит, и в любом случае обработать возможную ситуацию, когда введена строка вместо числа, чтобы приложение не падало

public class Calculator {
String goods ="";
double sum = 0.00;
double sum1 = 0.00;
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Не очень информативные названия для переменных, коллегам будет трудно понимать. И sum1 используется только в методе totalSum, можно туда и перенести её.

System.out.println(String.format(message,sum/persons) + message1);
}
else {
System.out.println(String.format(message,sum/persons) + message3);
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Код System.out.println(String.format(message,sum/persons) + <...>); повторяется, его можно вынести вниз, после if-else, оставив в проверке только определение слово рубль

String message3 ="рублей";
sum1 = Math.floor(sum/persons);

if (sum1%10>=2||sum1%10<=4) {
Copy link

@MagicUnderHood MagicUnderHood Aug 24, 2022

Choose a reason for hiding this comment

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

Если сумма будет оканчиваться на 5, окончание будет "рубля" вместо "рублей". Потому что условие здесь должно быть &&, то есть "и", а не || ("или"). Сейчас сначала идет проверка, что число >=2, если так и есть, то входим в первую ветку, а должна быть ещё проверка, что число <=4

double sum = 0.00;
double sum1 = 0.00;
String goods ="";// Строка, хранящая перечень всех товаров
double sum = 0.00;// Строка, хранящая сумму всех товаров
Copy link

Choose a reason for hiding this comment

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

имелось ввиду не написать комментарии к переменным, а дать новое имя, которые лучше бы отражало суть переменной, например sumAllGoods

}
public void totalSum (int persons){
public void totalSum (int persons){// функция вычисления, сколько должен каждый
double sum1 = 0.00;
Copy link

Choose a reason for hiding this comment

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

так же здесь не понятно что такое sum1 и что в ней храниться

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

2 more reviewers

@Takexito Takexito Takexito left review comments

@MagicUnderHood MagicUnderHood MagicUnderHood left review comments

Reviewers whose approvals may not affect merge requirements

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

AltStyle によって変換されたページ (->オリジナル) /