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
112 changes: 112 additions & 0 deletions src/main/java/Check.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import java.util.Scanner;

public class Check {
public static boolean isNumeric(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}
Comment on lines +4 to +15

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если проверять так, то получается, что тебе приходится каждый раз по 2 раза вызывать функцию parseInt - сначала для проверки, а второй раз чтобы получить число после проверки. Можно обойтись одним вызовом, а у класса Scanner есть функции hasNextInt и hasNextFloat, которые помогут избежать лишних вызовов парсинга


public static boolean isDouble(String str)
{
try
{
Double.parseDouble(str);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}

public static String enter()
{
Scanner in = new Scanner(System.in);
return in.next();
}

public static String countPeople(String enter)
{
boolean flag = true;
while(flag)
{
if(isNumeric(enter))
{
int countPeople = Integer.parseInt(enter);
Comment on lines +41 to +43

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вот тут получается два вызова Integer.parseInt, один в вызове функции isNumeric, второй - при присовении значения переменной countPeople. Можно здесь обойтись одним вызовом

if(countPeople == 1)
{
System.out.println("Количество человек, должно быть больше единицы. Введите значение больше единицы.");
enter = enter();
}
else if (countPeople < 1)
{
System.out.println("Ошибка, введите число больше единицы.");
enter = enter();
}
else
{
flag = false;
}
}
else
{
System.out.println("Некорректный ввод.Введите числовое значение, больше единицы.");
enter = enter();
}
}
return enter;
}
public static double checkPrice(String enter)
{
boolean flag = true;
while(flag)
{
if (isDouble(enter.replace(',','.')))
{
if(Double.parseDouble(enter) <= 0)
{
System.out.println("Ошибка, введите числовое значение, больше нуля");
enter = enter().replace(',','.');
}
else
{
flag = false;
}
}
else
{
System.out.println("Ошибка, введите числовое значение");
enter = enter().replace(',','.');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Много где повторяется enter().replace(',','.');, это можно вынести в отдельную функцию

}
}
return Double.parseDouble(enter.replace(',','.'));
}

public static String print(double result)
{
String[] a = String.valueOf(result).split("[.]");
int integralPart = Integer.parseInt(a[0]);
int endOne = integralPart%10;
int endTwo = integralPart%100;
Comment on lines +95 to +98

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Чтобы получить последние две цифры числа не обязательно нужно работать со строкой и парсить заново. Можно чисто операциями деления добиться двух последних цифр числа, например:
последнюю цифру можно получить, взяв остаток от деления на 10
последние 2 цифры - остаток от деления на 100

if(endOne == 1){
return " рубль";
}
else if((endOne > 1 && endOne < 5) && !(endTwo>=11 && endTwo<=14)){
return " рубля";
}
else if(endTwo >= 11 && endTwo <= 14){
return " рублей";
}
else{
return " рублей";
}
}
}
13 changes: 9 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
public class Main
{
public static void main(String[] args)
{
System.out.println("Добро пожаловать в приложение калькулятор!");
System.out.println("На скольких человек, вы планируете разделить счет?");
String enteredValue = Check.enter();
int countPeople = Integer.parseInt(Check.countPeople(enteredValue));
Products.productAll(countPeople);
}
}
83 changes: 83 additions & 0 deletions src/main/java/Products.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Products {
String name;
double price;

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

public String getNameOrPrice() {
String rubs = Check.print(price);
String formattedDouble = new DecimalFormat("#0.00").format(price);
formattedDouble = formattedDouble.replace(',','.');
return name + " цена: " + formattedDouble + rubs;
}

static double onePeople(int countPeople, double allPriceProduct)
{
return allPriceProduct/countPeople;
}

static void productAll(int countPeople) {
Scanner in = new Scanner(System.in);
//boolean flag = true;
List<Products> products = new ArrayList<>();
double allPriceProduct = 0.00f;
while (true) {
System.out.println("Введите название продукта:");
String nameProduct = in.next();
System.out.println("Введите цену на данный товар:");
String enterPrice = in.next();
enterPrice = enterPrice.replace(',', '.');
if (Check.isDouble(enterPrice)) {
double priceProduct = Double.parseDouble(enterPrice);
if (priceProduct <= 0)
{
priceProduct = Check.checkPrice(enterPrice);
allPriceProduct += priceProduct;
Products product = new Products(nameProduct, priceProduct);
products.add(product);
}
else
{
allPriceProduct += priceProduct;
Products product = new Products(nameProduct, priceProduct);
products.add(product);
}
} else {
double priceProduct = Check.checkPrice(enterPrice);
allPriceProduct += priceProduct;
Products product = new Products(nameProduct, priceProduct);
products.add(product);
}

System.out.println("Хотите ли вы ввести еще один продукт? Да - введите любой символ, нет - введите 'завершить'.");
String answer = in.next();
if (answer.equalsIgnoreCase("Завершить")) {
//flag = false;
break;
}
}
double priceForOne = onePeople(countPeople, allPriceProduct);
String formattedDouble = new DecimalFormat("#0.00").format(priceForOne);
formattedDouble = formattedDouble.replace(',','.');
double result = Double.parseDouble(formattedDouble);
System.out.println("Добавленные товары:");
for(Products products1 : products) {
System.out.println(products1.getNameOrPrice());
}
String formattedDoubleTwo = new DecimalFormat("#0.00").format(allPriceProduct);
formattedDoubleTwo = formattedDoubleTwo.replace(',','.');
String rubsOne = Check.print(allPriceProduct);
System.out.println("Общая сумма: " + formattedDoubleTwo + " " + rubsOne);
String rubs = Check.print(result);
System.out.println("К оплате для одного человека: " + result + rubs);
}
}