Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Проектная работа No1 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Vasil9202 wants to merge 5 commits into main
base: main
Choose a base branch
Loading
from master
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
View file Open in desktop

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
View file Open in desktop

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
View file Open in desktop

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

10 changes: 10 additions & 0 deletions .idea/misc.xml
View file Open in desktop

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
View file Open in desktop

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

2 changes: 1 addition & 1 deletion settings.gradle
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ dependencyResolutionManagement {
mavenCentral()
}
}
rootProject.name = "BillCalculator"
rootProject.name = "Java-Module-Project"
107 changes: 95 additions & 12 deletions src/main/java/Calculator.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,22 +1,105 @@
class Calculator {
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

int friendsCount;
public class Calculator {

String cart = "Добавленные товары:";
double totalPrice = 0;
private int humanCount;
Copy link

@MagicUnderHood MagicUnderHood Nov 23, 2022

Choose a reason for hiding this comment

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

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

private static final Scanner scanner = new Scanner(System.in);
private List<Product> productsList;
Copy link

@MagicUnderHood MagicUnderHood Nov 23, 2022

Choose a reason for hiding this comment

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

Переменная инициализируется, но не используется

private static double priceAllProducts = 0;

public Calculator(){
humanCount = divideBuild();
this.productsList = addProducts(humanCount);

Calculator(int friendsCount) {
this.friendsCount = friendsCount;
}

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;
public static int divideBuild(){
while (true){
try{
System.out.println("На скольких человек необходимо разделить счёт?");
int count = Integer.parseInt(scanner.nextLine());
Copy link

@MagicUnderHood MagicUnderHood Nov 23, 2022

Choose a reason for hiding this comment

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

Можешь применить в студии автоформатирование (в выбранном файле, сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L), тогда автоматически код выправится

if(count < 1){
System.out.println("Ошибка. Введено некорректное значение для подсчёта. Попробуйте снова");
}
else if(count == 1){
System.out.println("Нет смысла ничего считать и делить. Попробуйте снова");
}
else {
return count;
}}catch (Exception e){
System.out.println("Ошибка. Попробуйте снова.");
}
}
}

System.out.println(item.name + " в корзине");
public static List<Product> addProducts(int humanCount){
List<Product> list = new ArrayList<>();
while(true){
System.out.println("Введите название одного товара или слово \"Завершить\" для подсчета стоимости");
String product = scanner.nextLine();
if(product.equalsIgnoreCase("Завершить")){
if(list.size() == 0){
System.out.println("Товар не был введен, программа завершена.");
}
else {
System.out.println("Добавленные товары:");
for(Product products : list){
System.out.println(products.getName());
}
double pay = priceAllProducts / humanCount;
//double pay2 = Math.floor(pay);
String payformat = String.format("%.2f", pay);
String rub = floor(pay);
System.out.println("Каждый человек из " + humanCount +" должен заплатить " + payformat + " " + rub);
}
break;}
System.out.println("Введите стоимость товара в формате: 'рубли.копейки'");
try{
String price0 = scanner.nextLine();
Double price = Double.parseDouble(price0);
priceAllProducts += price;
list.add(new Product(product,price));}
catch (NumberFormatException e){
System.out.println("Задан неверный формат стоимости, начните заново");
}
}
return list;
}

double divideSum() {
return totalPrice / friendsCount;
private static String floor(double pay){
String rub = Integer.toString((int)Math.floor(pay));
if(rub.length() == 1){
switch (rub) {
case "0":
case "5":
case "6":
case "7":
case "8":
case "9":
return "рублей";
Copy link

@MagicUnderHood MagicUnderHood Nov 23, 2022

Choose a reason for hiding this comment

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

Можно все эти варианты оставить на последнюю ветку default

case "1":
return "рубль";
case "2":
case "3":
case "4":
return "рубля";
}
}
else if(rub.length() > 1){
Copy link

@MagicUnderHood MagicUnderHood Nov 23, 2022

Choose a reason for hiding this comment

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

Проверку можно упростить, если использовать (int) Math.floor(pay), и от него брать %10 для вычисления последней цифры и %100 для выяснения, что число между 11 и 19

int lastDigit = Integer.parseInt(Character.toString(rub.charAt(rub.length()-1)));
if(rub.length() == 2 && rub.charAt(0) == '1'){return "рублей!!";}
else if(lastDigit >= 5 && lastDigit <= 9 )
return "рублей";
else if(lastDigit >= 2 && lastDigit <= 4 )
return "рубля";
else if(lastDigit == 1)
return "рубль";
else
return "рублей";
}
return "Ошибка";
}
}
17 changes: 0 additions & 17 deletions src/main/java/Formatter.java
View file Open in desktop

This file was deleted.

10 changes: 0 additions & 10 deletions src/main/java/Item.java
View file Open in desktop

This file was deleted.

46 changes: 3 additions & 43 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,49 +1,9 @@
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int friendCount;
while (true) {
System.out.println("На сколько человек необходимо разделить счет?");
friendCount = scanner.nextInt();

if (friendCount > 1) {
break;
} else if (friendCount == 1) {
System.out.println(
"Нет смысла делить сумму на одного человека. Давайте попробуем ввести другое значение, которое будет больше единицы.");
} else {
System.out.println("Неверное количество друзей. Значение должно быть болье единицы, давайте попробуем еще раз.");
}
}

Calculator calculator = new Calculator(friendCount);

while (true) {
System.out.println("Введите название товара");
String name = scanner.next();

System.out.println("Введите стоимость товара в формате: 'рубли.копейки' [10.45, 11.40]");
double price = scanner.nextDouble();

calculator.addItem(new Item(name, price));

System.out.println(
"Хотите добавить еще один товар? Введите любой символ для продолжения, либо 'Завершить' если больше нет товаров для добавления");
String answer = scanner.next();

if (answer.equalsIgnoreCase("Завершить")) {
break;
}
}

double result = calculator.divideSum();
Formatter formatter = new Formatter();
Calculator calculator = new Calculator();
Copy link

@MagicUnderHood MagicUnderHood Nov 23, 2022

Choose a reason for hiding this comment

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

Переменная не используется. Можно методы divideBuild и addProducts вызывать отсюда, чтобы выполнение программы было более прозрачным, а не в конструкторе

// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
}
}
18 changes: 18 additions & 0 deletions src/main/java/Product.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
public class Product{
private String name;
private double price;

public String getName() {
return name;
}

public double getPrice() {
return price;
}

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

}

AltStyle によって変換されたページ (->オリジナル) /