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
39 changes: 39 additions & 0 deletions src/main/java/Calculate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import java.io.IOException;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Calculate {
Scanner scanner = new Scanner(System.in);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

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://www.baeldung.com/bufferedreader-vs-console-vs-scanner-in-java

String productName;
double productCost = 0;
String productInfo = "";
double productSum = 0;

void productInfo() throws IOException {
System.out.println("Введите, пожалуйста, наименование товара.");
productName = scanner.next();
productInfo = productInfo + " \n" + productName;

System.out.println("Введите, пожалуйста, стоимость товара.");
boolean isNumber;
do {
isNumber = true;
String string = bufferedReader.readLine();

try {
productCost = Double.parseDouble(string);
if (productCost < 0) {
System.out.println("Введите положительное число.");
isNumber = false;
}
} catch (Exception exception) {
isNumber = false;

System.out.println("Введено недопустимое значение.\nПожалуйста, введите число.");
}
}
while (!isNumber);
productSum = productSum + productCost;
}
}
49 changes: 45 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,47 @@

import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
public static void main(String[] args) throws IOException {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

PersonsNumber personsNumber = new PersonsNumber();
Scanner scanner = new Scanner(System.in);
personsNumber.personsNumber();
Calculate calculate = new Calculate();
while (true) {
calculate.productInfo();
System.out.println("Нужно ввести ещё товар? \nЕсли нет - напишите 'Завершить'");
String answer = scanner.next();
if (answer.equalsIgnoreCase("Завершить")) {
break;
}
}
double res = calculate.productSum / personsNumber.number;

String result = String.format("%.2f", res);
String sum = String.format("%.2f", calculate.productSum);
System.out.print("Добавленные товары:" + calculate.productInfo + "\nОбщая сумма чека: " + sum);
double i = Math.floor(calculate.productSum) % 100 / 10;
int k = (int) (calculate.productSum) % 10;

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 ((int) (i) == 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.

В таких случаях возможно использование конструкции switch - case, https://javarush.com/groups/posts/operator-switch-v-java

System.out.println(" рублей.");
} else if (k == 1) {
System.out.println(" рубль.");
} else if (k == 2 | k == 3 | k == 4) {
System.out.println(" рубля.");
} else {
System.out.println(" рублей.");
}
Comment on lines +24 to +32

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь и с 36 по 44 строку код идентичен, в таких случаях точно выносят его в отдельный метод и вызывают повторно в требуемых местах

System.out.print("Каждый человек должен заплатить " + result);
double y = Math.floor(res) % 100 / 10;
int x = (int) (res) % 10;
if ((int) (y) == 1) {
System.out.println(" рублей.");
} else if (x == 1) {
System.out.println(" рубль.");
} else if (x == 2 | x == 3 | x == 4) {
System.out.println(" рубля.");
} else {
System.out.println(" рублей.");
}
}
}
}

36 changes: 36 additions & 0 deletions src/main/java/PersonsNumber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PersonsNumber {
int number;
void personsNumber() throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Сколько человек будет оплачивать счёт?");
number = 0;
boolean isNumber;
do {
isNumber = true;
String string = bufferedReader.readLine();

try {
number = Integer.parseInt(string);
if (number <= 1) {
System.out.println("Количество человек должно быть более одного.");
isNumber = false;
}
} catch (Exception exception) {
isNumber = false;

System.out.println("Введено недопустимое значение.\nПожалуйста, введите число.");
}
}
while (!isNumber);
if (number < 5) {
System.out.println("Отлично!\nБудем делить на " + number + " персоны.");
} else {
System.out.println("Отлично!\nБудем делить на " + number + " персон.");
}
}
}
4 changes: 4 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
public class Product {
String productName;
double productCost = 0;
}