Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions src/main/java/Calc.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import java.util.Locale;
import java.util.Scanner;
public class Calc {

public static void Calculator() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно код ниже выполнять в отдельном методе, назвать его так, чтобы он отражал работу внутри, например, inputGoods, и вызывать этот метод в Main

Scanner scanner = new Scanner(System.in);
String result = "";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

double count = 0;
boolean cont = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно избавиться от переменной, если писать while(true), а в месте, где нужно выйти из цикла - писать break;

//создаем бесконечный цикл вызова товара
while (cont) {
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.

Можно дописать "Введите Завершить, чтобы закончить ввод", иначе пользователь не поймёт, что следует ввести для выхода

String res = scanner.next();
// устанавливаем слово для остановки цикла
if (res.toUpperCase(Locale.ROOT).equals("ЗАВЕРШИТЬ")) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Или можно использовать equalsIgnoreCase()

cont = false;
} else {
result += res + "\n";
System.out.println("Введите стоимость в формате: \'рубли.копейки' ");
String temp = scanner.next();
// проверка на то чтобы пользователь вводил только int стоимость
if (!checkPrice(temp)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно использовать scanner.hasNextFloat()

System.out.println("Некорректные данные");
} else {
System.out.println("Товар " + res + " успешно добавлен");
count += Double.parseDouble(temp);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно использовать scanner.nextFloat()

}
}
}
//Вывод будет одинаковый вне зависимости от того, какие данные укажет пользователь

double bill = count / Users.users;

String resultMessage = ("Общая стоимость: %.2f RUB");
System.out.println(String.format(resultMessage, count));

System.out.println("Сумма на одного человека: " + String.format("%.2f", bill) + " " + rubles(bill));
}
//реализация проверки
public static boolean checkPrice(String next) {
boolean isDigit = true;
for (int i = 0; i < next.length(); i++) {
if (!Character.isDigit(next.charAt(i)) && next.charAt(i) != '.') {
isDigit = false;
break;
}
}
return isDigit;

}
public static String rubles(double a) {
int rub = (int) Math.floor(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.

Отлично, что используешь переменную, всё сделано правильно

if (rub % 100 > 5 && rub <= 20) {
return "рублей";
} else if (rub % 10 == 1) {
return "рубль";
} else if (rub % 10 > 1 && rub % 10 < 5) {
return "рубля";
}
return "рублей";
}

}

11 changes: 6 additions & 5 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
public class Main {

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");

//main используем только для обращения к методам
Users.persons();
Calc.Calculator();
System.out.println("Спасибо за пользование нашим приложением!");
}
}
}
30 changes: 30 additions & 0 deletions src/main/java/Users.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import java.util.Scanner;

public class Users {
public static int users;

public static void persons() {
Scanner scanner = new Scanner(System.in);
//вводим бесконечный цикл, чтобы пользователь мог ввести правильное значение

while (true) {
System.out.println("Выберите количество человек");

if (scanner.hasNextInt()) {
users = scanner.nextInt();
if (users>1) {
System.out.println("Колличество пользователей = " + users);
break;
}
if(users<=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.

Можно поставить else к предыдущему if вместо этого кода

System.out.println("Введите корректные данные. Значение должно быть больше 1");
}
} else {
System.out.println("Введите корректные данные");
scanner.nextLine();
}
}

}

}