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: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
# Пустой репозиторий для работы с Java кодом в Android Studio

Реализован калькулятор:
все заказанные товары складываются в общий счет, который делится поровну между всеми участниками компании.
55 changes: 55 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import java.util.ArrayList;
import java.util.Scanner;

public class Calculator {
public int personCount;
public double totalPriceSum;
public double dividedSum;
public ArrayList<Product> products = new ArrayList<>();
private final Scanner scanner = new Scanner(System.in);

Calculator(int personCount){
this.personCount = personCount;
}
public void addToCart(){
while (true) {
System.out.println("\nВведите название товара:");
String inputName = scanner.nextLine();
if(inputName.trim().equalsIgnoreCase("завершить")) {
break;
}

System.out.println("Введите его стоимость в формате 'рубли.копейки':");
while (true) {
String inputPrice = scanner.nextLine();
try
{
double price = Double.parseDouble(inputPrice);
if(price < 0) {
System.out.println("Стоимость не может быть отрицательной. Повторите ввод:");
} else {
System.out.printf("Принято: товар '%s' с ценой %.2f успешно добавлен в корзину!%n", inputName, price);
totalPriceSum += price;
products.add(new Product(inputName, price));
System.out.println("Если хотите добавить еще товары, продолжайте ввод, иначе введите 'Завершить'");
break;
}
}
catch (NumberFormatException e)
{
System.out.println("Неверный формат: введите стоимость товара в формате 'рубли.копейки':");
}
Comment on lines +38 to +41

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

а как тогда можно написать чтобы не возникло исключения при парсинге в тип double?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

то есть если пользователь ввел буквы, вместо числа, то программа упадет, если не обернуть в блок try catch

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

можно сделать, например, как здесь https://github.com/DetroitRW/Java-Module-Project-YP/blob/dev/src/main/java/Main.java (методы readDouble(), readPrice())
в начале проверяем, что введен double, потом проверяем на условие >2 и если не подходит, то снова запрашиваем double

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

поподробнее почему так нельзя делать можно почитать в книге Java: Эффективное программирование Джошуа Блох глава 10.1. Используйте исключения только в исключительных ситуациях

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Спасибо за информацию) обязательно ознакомлюсь

}
}
}

public String calculate() {
dividedSum = totalPriceSum / personCount;

// определяем, с каким окончанием нужно закончить фразу: "рубль/рубля/рублей"
Formatter formatter = new Formatter();
String phraseEnd = formatter.getPhraseEnd(dividedSum);

return String.format("Все должны заплатить по %.2f %s", dividedSum, phraseEnd);
}
}
9 changes: 9 additions & 0 deletions src/main/java/Formatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Formatter {
public String getPhraseEnd(double dividedSum) {
return switch ((int) dividedSum % 10) {
case 1 -> "рубль";
case 2, 3, 4 -> "рубля";
default -> "рублей";
};
}
}
45 changes: 44 additions & 1 deletion src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,49 @@
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");

Scanner scanner = new Scanner(System.in);

// количество гостей
int personCount;

// 1. Входные параметры для счётчика
while (true) {
System.out.println("На скольких человек необходимо разделить счёт?");
String input = scanner.nextLine();

try
{
personCount = Integer.parseInt(input);
if(personCount == 1) {
System.out.println("Счет делить не требуется. Завершаем программу");
return;
} else if(personCount < 1) {
System.out.println("Неверный формат: введите положительное число");
} else {
System.out.println("Принято: количество человек: " + personCount);
break;
}
}
catch (NumberFormatException e)
{
System.out.println("Неверный формат: введите целое число.");
}
}

// создание калькулятора
Calculator calculator = new Calculator(personCount);

// 2. Добавление товаров в калькулятор
calculator.addToCart();

System.out.println("Добавленные товары:");
for(Product product : calculator.products){
System.out.printf("%s %.2f%n", product.name, product.price);
}

// 3. Расчет и вывод результата
System.out.println(calculator.calculate());
}
}
9 changes: 9 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Product {
String name;
double price;

public Product(String name, double price) {
this.name = name;
this.price = price;
}
}