Skip to content

Conversation

@YegUsh
Copy link

@YegUsh YegUsh commented Oct 30, 2022

Честно, думаю можно сделать гораздо лучше
Очень жду корректировок с Вашей стороны

System.out.println("В таком случае нет смысла считать :\nВведите значение еще раз: ");
while (!scanner.hasNextInt()) {
scanner.next();
}

Choose a reason for hiding this comment

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

Можно добавить System.out.println("Вы ввели неверное значение, попробуйте еще раз: ");, иначе будет запрашиваться число, но пользователю ничего не выведется, он может не понять, что от него ждут

System.out.println("Значение меньше нуля, попробуйте еще раз:");
while (!scanner.hasNextFloat()) {
scanner.next();
}

Choose a reason for hiding this comment

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

Тут тоже можно добавить System.out.println("Вы ввели неверное значение, попробуйте еще раз: ");

public class Calculator {
float priceForPerson;
String outputCalculate;
String rub;

Choose a reason for hiding this comment

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

Можно сделать 3 переменные приватными

if (priceForPerson%10 == 1) {
rub = "рубль";
}
else if (priceForPerson%10 == 2 && priceForPerson%10 == 3 && priceForPerson%10 == 4){

Choose a reason for hiding this comment

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

Можно упростить условие: priceForPerson%10 >= 2 && priceForPerson%10 <= 4

}

void correctOutput() {
if (priceForPerson%10 == 1) {

Choose a reason for hiding this comment

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

priceForPerson%10 считается несколько раз, лучше посчитать 1 раз и записать в переменную

rub = "рубля";
}
else {
rub = "рублей";

Choose a reason for hiding this comment

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

Стоит учесть, что для чисел 11-19 окончание слова - "рублей". Для обработки можно до этого if-else написать ещё один, с проверкой (например, priceForPerson%100 >= 11 и <= 19, или другим вариантом)

rub = "рублей";
}
outputCalculate = String.format("%.2f", priceForPerson);
System.out.println("Каждый человек должен заплатить по: " + outputCalculate + " " + rub);

Choose a reason for hiding this comment

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

Хорошо, что повторяющийся код вынесен за if-else, молодец

System.out.println("Вы ввели неверное значение, попробуйте еще раз: ");
}
int amountOfPersons = scanner.nextInt();
while (amountOfPersons < 2) { // если значенние 0,1 или отрицательное, запрашиваем ввод снова

Choose a reason for hiding this comment

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

Можно вместо 3 while сделать так: один бесконечный цикл while(true), до него объявить переменную amountOfPersons, после него идет строчка 20 с выводом количества персон. В самом бесконечном цикле if-else, в условии проверяем, ввели ли значение типа int, если нет, то как у тебя строчки 9-10, если да - считываем инт значение в amountOfPersons и затем проверяем в if-else, если <2, то как ты выводишь, что считать нечего, иначе - break; выходим из цикла. Это немного уберет дублирование ввода при неверном значении

float totalSumOfProducts; // переменная отвечающая за суммирование
String nameOfProduct; // строка содержащая название продукта
String totalProducts = ""; // строка сохраняющая все продукты
String endOfCalculate; // строка для завершения бесконечного цикла

Choose a reason for hiding this comment

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

Тут тоже можно сделать переменные приватными, если вне класса они не используются

}

void testFloatPrice() { // проверка значения float
while(!scanner.hasNextFloat()) {

Choose a reason for hiding this comment

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

Можно преобразовать алгоритм метода по аналогии с вводом количества человек

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