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

Консольное приложение #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
KotlinPunk wants to merge 1 commit into main
base: main
Choose a base branch
Loading
from dev
Open
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
87 changes: 87 additions & 0 deletions src/main/java/Calculator.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.ArrayList;

public class Calculator {

public static String calculator(int N) {
Copy link

@Charmandik Charmandik Mar 1, 2024

Choose a reason for hiding this comment

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

старайся избегать использования статических функций, так как они не очищаются и всегда занимают место в памяти

Copy link
Owner Author

@KotlinPunk KotlinPunk Mar 1, 2024

Choose a reason for hiding this comment

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

Понял. Но вроде в курсе ещё не встречал эту информацию)


ArrayList<Product> products = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
double sum = 0;

while (true) {

System.out.println("Пожалуйста, введти название товара: ");
String productName = prod(scanner);

System.out.println("Пожалуйста, укажите в формате 'рубли,копейки' стоимость товара: ");
double priceProduct = prPr(scanner);
sum += priceProduct;

products.add(new Product(productName, priceProduct));
System.out.println("Товар успешно добавлен");

System.out.println("Будут ли ещё товары? Если нет, пожалуйста, введите 'Завершить'.");
String z = scanner.next();
Copy link

@Charmandik Charmandik Mar 1, 2024

Choose a reason for hiding this comment

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

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

KotlinPunk reacted with thumbs up emoji


if(z.equalsIgnoreCase("Завершить")) {

for (int i = 0; i < products.size(); i++) {
Product product = products.get(i);
System.out.println("Товар: " + product.productName + ", стоимость товара: " + product.priceProduct + ".");
}

double midSum = sum/N;

String form = String.format("%.2f", midSum);
String f = rub(midSum);
return form + f; // возвращаем средний чек на человека
}
}
}

public static String prod (Scanner scanner) {
while (true) {
try {
String productName = scanner.next();
return productName;
} catch (InputMismatchException q) {
System.out.println("Введено некорректно название товара.");
} finally {
scanner.nextLine();
}
}
}
public static double prPr (Scanner scanner) {
while (true) {
try {
double prPr = scanner.nextDouble();
if (prPr <= 0) {
System.out.println("Введена отрицательная или нулевая стоимость товара. Повторите ввод, пожалуйста.");
} else {
return prPr;
}
} catch (InputMismatchException q) {
System.out.println("Введена некорректная стоимость товара.");
} finally {
scanner.nextLine();
}
}
}
public static String rub(double midSum) {
double v = Math.floor(midSum);
if (v % 100 >= 11 && v % 100 <=14) {
Copy link

@Charmandik Charmandik Mar 1, 2024

Choose a reason for hiding this comment

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

для ситуаций когда 2 и более условия, почти всегда лучше использовать switch/case

KotlinPunk reacted with thumbs up emoji
return " рублей";
} else if (v % 10 == 1) {
return " рубль";
} else if (v % 10 == 2 || v % 10 == 3 || v % 10 == 4) {
return " рубля";
}else {
return " рублей";
}
}
}


35 changes: 33 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,37 @@
import java.util.Scanner;
import java.util.InputMismatchException;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
System.out.println("На скольких человек необходимо разделить счёт?");
Scanner scanner = new Scanner(System.in);
int numberOfPeople = 0; // хранит ответ пользователя

while (true) {

try {
numberOfPeople = scanner.nextInt();
} catch (InputMismatchException q) {
Copy link

@Charmandik Charmandik Mar 1, 2024

Choose a reason for hiding this comment

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

с одной стороны, когда ты используешь более конкретный класc ошибки, то ты как бы делаешь свой код более точным, но с другой стороны, если произойдет любая другая ошибка, то твой код упадет и всё сломается, поэтому если на это нет острой необходимости, то проще использовать просто класс Exception

Copy link
Owner Author

@KotlinPunk KotlinPunk Mar 1, 2024

Choose a reason for hiding this comment

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

Вот тут я просто глядел форумы. Искал ответ, как лучше будет. Поэтому решил оставить так. Но я вас понял. Спасибо.

System.out.println("Введено не целое число.");
} finally {
scanner.nextLine();
}

if (numberOfPeople == 1) {

System.out.println("В этом случае нет смысла ничего считать и делить.");

} else if (numberOfPeople < 1) {

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

} else if (numberOfPeople > 1) {

String s = Calculator.calculator(numberOfPeople);

System.out.println("Каждый заплатит: " + s + ".");
}
}
}
}
}

10 changes: 10 additions & 0 deletions src/main/java/Product.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
public class Product {

String productName;
double priceProduct;

public Product (String productName, double priceProduct) {
this.productName = productName;
this.priceProduct = priceProduct;
}
}

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