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
s77sa wants to merge 3 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
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"
102 changes: 89 additions & 13 deletions src/main/java/Calculator.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,22 +1,98 @@
class Calculator {
import java.util.Scanner;

int friendsCount;

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

Calculator(int friendsCount) {
this.friendsCount = friendsCount;
public class Calculator {
// Метод добавления количества персон
public int addPerson(){
int person = -1;
Scanner input = new Scanner(System.in);
while (person <= 0) {
System.out.println("Введите количество персон");
if (input.hasNextInt()) {
person = input.nextInt();
if (person <= 0) {
System.out.println("Вы ввели не верное количесво персон");
}
} else {
System.out.println("Вы ввели ошибочное значение");
input.next(); // Сдвиг сканера, иначе бесконечный цикл
}
}
return person;
}

void addItem(Item item) {
totalPrice += item.price;
cart = cart + "\n" + item.name;
private Product addProduct(){
String name = null;
double cost = -1;
Product product;
Scanner input = new Scanner(System.in);
System.out.println("Введите название продукта");
// В название принимается любое значение
if(input.hasNext()) {
name = input.next();
}

System.out.println(item.name + " в корзине");
System.out.println("Введите стоимость продукта в формате \"рубли,копейки [10,45]\"");
while (cost <= 0) {
if (input.hasNextDouble()) {
cost = input.nextDouble();
}
else {
System.out.println("Вы ввели не корректную стоимость");
input.next(); // Сдвиг
}
}
System.out.println("Вы добавили товар: \"" + name + "\" стоимостью: " + cost);
product = new Product(name,cost);
return product;
}

double divideSum() {
return totalPrice / friendsCount;
//Получить список всех продуктов и финальную стоимость
public double summProducts()
{
String productsAllPerson = "";
double costAllPerson = 0;
Scanner input = new Scanner(System.in);
String answer;
Product product;
String strDialog;
while(true) {
System.out.println("Хотите ли Вы добавить новый продукт? (Да/Нет/Завершить)");
if (input.hasNext()) {
answer = input.next();
if (answer.equalsIgnoreCase("да")) {
product = addProduct();
productsAllPerson = productsAllPerson + product.productName + "\n";
costAllPerson = costAllPerson + product.cost;
}
if (answer.equalsIgnoreCase("нет") || answer.equalsIgnoreCase("завершить")) {
break;
}
}
}
strDialog = "Добавленные товары:\n%s\nОбщей стоимостью: %.2f %s";
strDialog = String.format(strDialog, productsAllPerson, costAllPerson, getEnding(costAllPerson));
System.out.println(strDialog);
return costAllPerson;
}

// Склонение рубля
public String getEnding(double cost){
int preLast = (int)Math.floor(cost) % 100 / 10;
if (preLast == 1){
return "рублей";
}

switch ((int)Math.floor(cost) % 10){
case 1:
return "рубль";
case 2:
case 3:
case 4:
return "рубля";
default:
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.

56 changes: 16 additions & 40 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,49 +1,25 @@
import java.util.Scanner;
//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));
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет!");
Calculator calc = new Calculator();
// Запрашиваем количество персон у пользователя
int person = calc.addPerson();
// Запрашиваем список продуктов со стоимостью
double costAll = calc.summProducts();
double cost = costAll / person;
String dialog = "Каждый из друзей должен заплатить: %.2f %s";
dialog = String.format(dialog, cost, calc.getEnding(cost));
System.out.println(dialog);

System.out.println("Завершено!");
}

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

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

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

System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
}
}
8 changes: 8 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,8 @@
public class Product {
String productName;
double cost;
Product(String productName, double cost){
this.productName = productName;
this.cost = cost;
}
}

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