Repository navigation
Проектная работа №1. Калькулятор счёта #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
TanyaRul
wants to merge
3
commits into
main
Choose a base branch
from
master
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,22 +1,66 @@ | ||
| class Calculator { | ||
| import java.util.Scanner; | ||
|
|
||
| int friendsCount; | ||
| public class Calculator { | ||
|
|
||
| String cart = "Добавленные товары:"; | ||
| double totalPrice = 0; | ||
| public static String option; | ||
| public static String listOfProducts = ""; | ||
| public static double totalCost = 0; | ||
| public static double price; | ||
|
|
||
| Calculator(int friendsCount) { | ||
| this.friendsCount = friendsCount; | ||
| public static void addProduct() { | ||
| Scanner scanner = new Scanner(System.in); | ||
| while (true) { // Запускаем бесконечный цикл для добавления товаров | ||
| System.out.println("Введите название товара"); | ||
| Product productName = new Product(scanner.next()); // создаем объект класса Product и сохраняем в нем введённое пользователем значение | ||
| while (true) { // Запускаем бесконечный цикл для проверки цены | ||
| System.out.println("Введите стоимость товара в формате 'рубли.копейки' [10.45, 11.40]"); | ||
| if (scanner.hasNextDouble()) { // проверка на число | ||
| price = scanner.nextDouble(); | ||
| if (price > 0) { // проверка на положительное число | ||
| break; | ||
| } | ||
| else { | ||
| System.out.println("Цена товара не может быть отрицательной, введите положительное число в формате '10.45'"); | ||
| } | ||
| } | ||
| else { | ||
| System.out.println("Введено неверное значение, цена товара должна быть положительным числом в формате '10.45'"); | ||
| scanner.next(); // очистка ввода | ||
| } | ||
| } | ||
| System.out.println("Товар успешно добавлен"); | ||
| listOfProducts += productName.name + " - " + price; // добавляем новый товар в список | ||
| totalCost += price; // считаем текущую общую сумму | ||
| System.out.println(String.format("Текущая общая сумма: %.2f \n", totalCost)); | ||
| System.out.println("Для завершения процесса добавления товаров введите команду \"Завершить\" или любое другое значение для добавления ещё одного товара"); | ||
| option = scanner.next(); | ||
| if (option.equalsIgnoreCase("завершить")) { | ||
| System.out.println("Добавленные товары:\n" + listOfProducts + "\n" + String.format("Итого: %.2f", totalCost)); | ||
| break; | ||
| } | ||
| listOfProducts += "\n"; | ||
| } | ||
| } | ||
|
|
||
| void addItem(Item item) { | ||
| totalPrice += item.price; | ||
| cart = cart + "\n" + item.name; | ||
|
|
||
| System.out.println(item.name + " в корзине"); | ||
| public static void sumOutput() { // вывод итоговой суммы на каждого гостя | ||
| double amountPerGuest = totalCost / Guests.numberOfPerson; // считаем итоговую сумму на каждого гостя | ||
| int amountRound = (int)(Math.floor(amountPerGuest)); // округляем и приводим к целому числу | ||
| int lastDigit = amountRound % 10; // вычисляем последнюю цифру числа | ||
| if (amountRound > 10 && amountRound < 20) { | ||
| System.out.println(String.format("Каждый гость должен заплатить %.2f", amountPerGuest) + " рублей"); | ||
| } | ||
| else if (lastDigit > 1 && lastDigit < 5) { | ||
| System.out.println(String.format("Каждый гость должен заплатить %.2f", amountPerGuest) + " рубля"); | ||
| } | ||
| else if (lastDigit == 1) { | ||
| System.out.println(String.format("Каждый гость должен заплатить %.2f", amountPerGuest) + " рубль"); | ||
| } | ||
| else { | ||
| System.out.println(String.format("Каждый гость должен заплатить %.2f", amountPerGuest) + " рублей"); | ||
| } | ||
| } | ||
|
|
||
| double divideSum() { | ||
| return totalPrice / friendsCount; | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import java.util.Scanner; | ||
| public class Guests { | ||
|
|
||
| public static int numberOfPerson; | ||
|
|
||
| public static void addGuest () { | ||
| Scanner scanner = new Scanner(System.in); | ||
| while (true) { // Запускаем бесконечный цикл | ||
| System.out.println("Введите количество гостей"); | ||
| if (scanner.hasNextInt()) { | ||
| numberOfPerson = scanner.nextInt(); // получаем значение от пользователя | ||
| if (numberOfPerson > 1) { | ||
| Calculator.addProduct(); //вызываем метод добавления и подсчёта товаров из класса Сalculator | ||
| Calculator.sumOutput(); //вызываем метод вывода результата из класса Сalculator | ||
| break; | ||
| } | ||
| if (numberOfPerson == 1) { | ||
| System.out.println("Счёт делить не с кем"); | ||
| break; | ||
| } | ||
| System.out.println("Введите корректное количество гостей, значение должно быть больше 1"); | ||
| } | ||
| else { | ||
| System.out.println("Введено неверное значение, введите целое число больше 1"); | ||
| scanner.next(); | ||
|
|
||
| } | ||
| } | ||
| } | ||
| } |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,5 @@ | ||
| 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(); | ||
|
|
||
| System.out.println(calculator.cart); | ||
| System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result)); | ||
| Guests.addGuest (); // вызываем метод подсчёта гостей из класса Guests | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| public class Product { | ||
| String name; | ||
|
|
||
| Product (String productName) { | ||
| name = productName; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Код
System.out.println(String.format("Каждый гость должен заплатить %.2f", amountPerGuest) + " рублей");повторяется в каждой ветке, кроме слова рубль, лучше код вынести после if-else, оставив в нем только определение слова