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

Консольное приложение No1 #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

Open
DanilaLort wants to merge 4 commits into main
base: main
Choose a base branch
Loading
from dev
Open
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
94 changes: 92 additions & 2 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,96 @@
import java.util.Scanner;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class Main {
static int numOfPersons;
static double check = 0;
static Scanner scanner = new Scanner(System.in);
static ArrayList<Product> products = new ArrayList<>();
static Calculate calc = new Calculate();

public static void main(String[] args) {
System.out.println("Hello world!");
String s;
System.out.println("На скольких человек необходимо разделить счёт:");
s = scanner.next();

while (true) {
if (s.equalsIgnoreCase("завершить")) {
System.out.println("Программа завершена");
return;
}
if (s.matches("\\d+")) {
Copy link

@taikonavt taikonavt Feb 12, 2024

Choose a reason for hiding this comment

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

регулярные выражения это круто, но нужно много времени, чтобы с ними нормально разобраться. И если ты только начинаешь программировать, то я бы не стал пока что с ними заморачиваться. Они не очень часто используются

numOfPersons = Integer.parseInt(s);
if (numOfPersons == 1) {
System.out.println("Количество человек равно 1.\nЭто некорректное значение для подсчёта");
System.out.println("Введите количество человек:");
s = scanner.next();
} else if (numOfPersons < 1) {
System.out.println("Количество человек меньше 1.\nЭто некорректное значение для подсчёта");
System.out.println("Введите количество человек:");
s = scanner.next();;
} else break;
} else {
System.out.println("Это некорректное значение для подсчёта");
System.out.println("Введите количество человек:");
s = scanner.next();
}
}

while (true) {
System.out.println("Введите блюдо и цену.\nЕсли добавили все позиции введите 'Завершить'");
s = scanner.next();
if (!s.equalsIgnoreCase("завершить")) {
s += scanner.nextLine();
check += calc.calculate(s, products);
} else {
System.out.println("Добавленные товары:");
for (Product product : products) {
product.print();
}
if (check / numOfPersons > 1)
System.out.println(String.format("Итого: %.2f рубля с каждого", check / numOfPersons));
else
System.out.println(String.format("Итого: %.2f рубль с каждого", check / numOfPersons));
return;
}
}
}

public static class Calculate {
public static double calculate(String s, ArrayList products) {
Pattern pattern = Pattern.compile(" [0-9]*\\.?[0-9]+$");
Matcher matcher = pattern.matcher(s);
if (matcher.find())
if (matcher.start() > 1) {
double check = 0;
check += Double.parseDouble(s.substring(matcher.start(), matcher.end()));
Product product = new Product(s.substring(0, matcher.start() - 1), Double.parseDouble(s.substring(matcher.start(), matcher.end())));
product.printAdd();
products.add(product);
return check;
}
System.out.println("Некоректный ввод!\nВвод осуществляется в формате:Название блюда РУБЛИ.КОПЕЙКИ");
// System.out.println(s.substring(matcher.start(), matcher.end()));
return 0;
}
}

public static class Product {
Copy link

@taikonavt taikonavt Feb 12, 2024

Choose a reason for hiding this comment

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

Молодец, что добавил класс Product. Но на счет методов printAdd() и print() я бы подумал. Это все таки вывод текста в консоль, а класс Product должен содержать только логику относящуюся к product. Можно было бы например сделать метод
public void getStringProductWasAdd() { return "Блюдо: " + name + " по цене " + price + " рублей" + " добавленно"; } и в процессе выполнения программы вызвать System.out.println(getStringProductWasAdd()). Но это не сильно важно, просто на подумать.

Copy link

@taikonavt taikonavt Feb 12, 2024

Choose a reason for hiding this comment

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

Принцип единственной ответственности https://habr.com/ru/companies/ruvds/articles/426413/

private String name;
private double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
public void printAdd() {
System.out.println(String.format("Блюдо: %s по цене %.2f рублей добавленно", name, price));
}

public void print() {
System.out.println(String.format("Блюдо: %s по цене %.2f рублей", name, price));
}
}
}
}

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