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 .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 123 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions .idea/codeStyles/codeStyleConfig.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 57 additions & 0 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
public class Calculator {

private Product[] array = new Product[20];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше использовать список из коллекций - например, ArrayList, потому что размер массива ограничен, а теоретически количество товаров неограниченное

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.

Мой эррей же расширяется

private int size = 0;
double sum;
double sumForEach;
int nuberOfPpl;


public void addProduct(Product p) {
array[size] = p;
size++;
if (size == array.length) {
Product[] newArray = new Product[array.length * 2];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
array = newArray;
}
}

public void count() {
for (int i = 0; i < size; i++) {
sum = sum + array[i].productPrice;
sumForEach = sum / nuberOfPpl;
System.out.println("\n" + array[i].productName);
}
}

public void getNumberOfPpl(int a) {
nuberOfPpl = a;
}

public void nameOfCurrency() {
int rounded = (int) Math.floor(sumForEach);
rounded = rounded % 100;
if (rounded > 20) {
rounded = rounded % 10;
}
String summ = "\nСумма для каждого составляет: ";
if (rounded == 1) {
System.out.println(summ + sumForEach + " рубль.");
} else if (rounded >= 5) {
System.out.println(summ + sumForEach + " рублей.");
} else if (rounded > 1) {
System.out.println(summ + sumForEach + " рубля.");
} else if (rounded == 0)
System.out.println(summ + sumForEach + " рублей.");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Есть принцип, который называется DRY - Don't repeat yourself. По этому правилу, если видишь, что есть многократно повторяющиеся участки кода, то их можно объединить. Здесь, например, изменяется лишь окончание, поэтому можно сделать строку, которая будет изменяться в зависимости от rounded, и затем присоединять её к предложению

}







61 changes: 57 additions & 4 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,61 @@
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

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

Calculator add = new Calculator();
Scanner scanner = new Scanner(System.in);

do {
System.out.println("На скольких человек необходимо разделить счёт?");
numberOfPeople = 1;
try { numberOfPeople = scanner.nextInt();
if (numberOfPeople == 1) {
System.out.println("Ничего делить не надо");
} else if (numberOfPeople <= 0) {
System.out.println("Некорректное значение для подсчёта.");
}
add.getNumberOfPpl(numberOfPeople);//добавляем кол-во людей
} catch (InputMismatchException e) {
System.out.println("Не допустимое значение!");
scanner.next();
}
} while (numberOfPeople < 2);

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) {
System.out.println("Введите название товара");
productName = scanner.next();
if (productName.equalsIgnoreCase("Завершить")) {
break;
}
while (true) {
System.out.println("Введите стоимость товара в формате 'рубли.копейки' ");
try {
productPrice = scanner.nextDouble();
if (productPrice < 0) {
System.out.println("Не допустимое значение!");
} else {
Product product = new Product(productName, productPrice);
add.addProduct(product);//добавляем продукты
System.out.println("Товар добавлен, хотите ли вы добавить еще один товар? Если нет, введите: Завершить.");
break;}

} catch(InputMismatchException e){
System.out.println("Не допустимое значение!");
scanner.next();
}
}
}
typeGoods();
add.count();
add.nameOfCurrency();
}
private static void typeGoods() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Для простого вывода строки можно не создавать отдельный метод

System.out.print("Добавленные товары: ");
}
}
}
13 changes: 13 additions & 0 deletions src/main/java/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
public class Product {

String productName;
double productPrice;


public Product(String productName, double productPrice) {
this.productName = productName;
this.productPrice = productPrice;
}
}