Skip to content
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
# Пустой репозиторий для работы с Java кодом в Android Studio
# «Калькулятор счёта»
Консольное приложение, которое будет задавать вопросы в консоли, считывать пользовательский ввод и в результате показывать список товаров и сумму для каждого из друзей.
123 changes: 121 additions & 2 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,125 @@
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
public static double getDouble (Scanner scanner) {
try {
return scanner.nextDouble();
}
catch (InputMismatchException e) {
scanner.next();
return 0;
}
}
public static int getInt (Scanner scanner) {
try {
return scanner.nextInt();
}
catch (InputMismatchException e) {
scanner.next();
return 0;
}
}
public static class Formatter {
void printWithRubles (double x) {
int cutPoint = (int) Math.floor(x);
int rest = cutPoint % 10;
int rest1 = cutPoint % 100;
if (rest1 >= 10 && rest1 <= 19) {
System.out.printf("%.2f Рублей", x);
}
else if (rest == 0 || rest >= 5) {
System.out.printf("%.2f Рублей", x);
}
else if (rest == 1) {
System.out.printf("%.2f Рубль", x);
}
else if (rest >= 2) {
System.out.printf("%.2f Рубля", x);
}
}
}
public static class Product {
String name;
double price;

Product(String productName, double productPrice) {
name = productName;
price = productPrice;
}
}
public static class Calculator {
String productNames = "";
double productPrices = 0;

void addProduct(Product p) {
productPrices = productPrices + p.price;
productNames = productNames.concat(p.name).concat("\n");
System.out.println("Товар успешно добавлен!");
}

double divideByAll (int guests) {
return productPrices / guests;
}
}

public static int getGuests(Scanner scanner) {
int guests;
while (true) {
System.out.println("На сколько человек необходимо разделить счёт?");
guests = getInt(scanner);
if (guests > 1) {
break;
} else if (guests == 1) {
System.out.println("нет смысла ничего считать и делить");
} else {
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.

Такие отдельные логические блоки, как этот (ввод и обработка количества людей), а также логические блоки с вводом товаров и выводом результатов лучше выносить в отдельные методы и затем вызывать их там, где необходимо. Это позволяет улучшить читаемость кода, т.к. разнородная логика не смешивается в один сплошной код, а также упрощает поддержку кода.

return guests;
}

public static void getProducts(Scanner scanner, Calculator calc) {
while (true) {
System.out.println("Введите наименование товара или 'Завершить'");
String productName = scanner.next();
if (productName.equalsIgnoreCase("завершить")) {
break;
}
else {
while (true) {
System.out.println("Введите стоимость товара");
double productPrice = getDouble(scanner);
if (productPrice > 0) {
Product newProduct = new Product(productName, productPrice);
calc.addProduct(newProduct);
break;
}
else {
System.out.println("Это некорректное значение для подсчёта");
}
}
}
}
}

public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scanner = new Scanner(System.in);
int guests = getGuests(scanner);

Calculator calc = new Calculator();
getProducts(scanner, calc);

System.out.println("Добавленные товары:");
System.out.println(calc.productNames);
double result = calc.divideByAll(guests);
System.out.print("Каждый должен заплатить по: ");

Formatter f = new Formatter();
f.printWithRubles(result);

scanner.close();
}
}
}