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
15 changes: 15 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
public class Calculator {
double _amount;
String _listOfProducts = "Добавленные товаровы:";
private int _countProd = 0;
public void addProduct(String nameProd)
{
_listOfProducts = _listOfProducts + ("\n" + String.format("%d) ", _countProd) + nameProd);
}

public void riseAmount(double priceProd)
{
_amount += priceProd;
_countProd++;
}
}
106 changes: 103 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,108 @@
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {

private static String nounForm(double num)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше называть методы глаголами. Например, getNounForm. О правилах нейминга можно почитать здесь:
https://github.com/qcha/JBook/blob/master/start/code_style.md
Также эта тема хорошо раскрывается во 2 главе книги Роберта Мартина "Чистый код".

{
String numStr = Double.toString(num);
numStr = numStr.substring(0, numStr.indexOf("."));
if (num > 10) {
for (int i = 11; i < 15; i++) {
if (i == Integer.parseInt(numStr.substring(numStr.length() - 2))) {
return "рублей";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Решение обработки чисел с 11 до 14 с циклом работает, но, кажется, слишком усложнено)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Здравствуйте! Можете, пожалуйста, подсказать другой примерный вариант решения задачи, которая учитывает числа, оканчивающиеся на 11-14?

}
}
}
switch (numStr.charAt(numStr.length() - 1))
{
case '0':
case '5':
case '6':
case '7':
case '8':
case '9':
return "рублей";
case '1':
return "рубль";
case '2':
case '3':
case '4':
return "рубля";
default:
return "ERROR";
}
}

private static int askNumOfPeople()
{
Scanner sc = new Scanner(System.in);
int numOfPeople = 0;
System.out.println("На какое количство людей поделить чек?");
while (numOfPeople <= 1) {
while (true) {
try {
numOfPeople = sc.nextInt();
break;
} catch (Exception e) {
System.err.println("Невозможное значение. Введите натуральное число:");
sc.nextLine();
}

}
if (numOfPeople < 1) {
System.out.println("Значение меньше единицы. Введите натуральное число:");
} else if (numOfPeople == 1) {
System.out.println("Не имеет смысла считать");
}
}
return numOfPeople;

}

public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");

Calculator calc = new Calculator();

Scanner sc = new Scanner(System.in);

int numOfPeople = askNumOfPeople();
System.out.println("Теперь давайте выберем товары!");

while(true)
{
String prodName = null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если мы создаем переменную и не задаем ей изначальное значение, то она и так будет равна null, т.е. задавать ей null излишне

System.out.println("Введите название товара или 'завершить':");
prodName = sc.nextLine();
if (prodName.equalsIgnoreCase("завершить"))
{
System.out.println("Все товары добавлены!\n");
break;
}
System.out.println("Введите стоимость товара:");
double price = 0;
while(true)
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше фигурную скобку писать в той же строчке
while(true) { - таков кодстайл. Некритично, но в реальных проектах обычно стараются соблюдать единообразие стиля.

try{
price = sc.nextDouble();
if (price > 0){
break;
}
else{
System.err.println("Невозможное значение. Введите значение больше нуля:");
}
} catch (Exception e){
System.err.println("Невозможное значение. Введите коректное значение (дробные значения пишите с запятой):");
sc.nextLine();
}

}
sc.nextLine();
calc.riseAmount(price);
calc.addProduct(prodName);
System.out.println("Товар добавлен!\n");
}

System.out.println(calc._listOfProducts);
System.out.println(String.format("\nС каждого человека по %.2f %s", calc._amount / numOfPeople, nounForm(calc._amount / numOfPeople)));
}
}
2 changes: 2 additions & 0 deletions src/main/java/numOfPeople.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
public class numOfPeople {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Неиспользуемые классы лучше не хранить

}