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
personBit
wants to merge
1
commit into
dev
Choose a base branch
from
Calc
base: dev
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
| import java.util.Locale; | ||
|
|
||
|
|
||
| public class Calc { | ||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
|
|
||
| ArrayList<Item> items = new ArrayList<>(); // список товаров | ||
| int countPeople; // количество человек | ||
| int rubleFormat; // формат слова "рубль" | ||
| double totalPrice = 0; // стоимость всех товаров (изначально 0) | ||
| double fromEach; // каждый должен заплатить | ||
| public void countPeople() { // узнаем количество человек | ||
| System.out.println("Привет! На сколько человек делим счет (введите число)?:"); | ||
|
|
||
| do { | ||
| while (!scanner.hasNextInt()) { // пользователь ввел не число | ||
| System.out.println("Ошибка! Введите число:"); | ||
| scanner.next(); | ||
| } countPeople = scanner.nextInt(); | ||
| if (countPeople <= 1) { // пользователь ввел число меньше нуля, сообщаем об ошибке и начинаем снова | ||
| System.out.println("Должно быть минимум 2 человека для того, чтобы разделить счет. Повторите попытку:"); | ||
| } | ||
| } while (countPeople <= 1); | ||
|
|
||
| } | ||
|
|
||
| public void itemAdd(String name, double price) { // добавляем товар в список | ||
| Item newItem = new Item(); | ||
| newItem.name = name; | ||
| newItem.price = price; | ||
|
|
||
| items.add(newItem); | ||
| } | ||
| public void itemAddOut() { // внешний метод для добавления товара | ||
| scanner.useLocale(Locale.ENGLISH); | ||
| System.out.println("Введите название товара:"); | ||
| String name = scanner.next(); | ||
| double price; | ||
|
|
||
| System.out.print("Введите цену товара (в точности до копеек. Используйте точку в качестве разделения):\n"); | ||
| do { // пользователь добавит хотя-бы один товар | ||
| while (!scanner.hasNextDouble()) { // пользователь ввел не число, тогда | ||
| System.out.println("Ошибка! Введите число:"); | ||
| scanner.next(); | ||
| } | ||
| price = scanner.nextDouble(); // если ввел число, присвоем его переменной price | ||
| if (price <= 0) { // если число меньше нуля, выводим ошибку и переходим на while () | ||
| System.out.println("Число должно быть больше нуля. Попробуйте снова:"); | ||
| } | ||
| } while (price <= 0); // в случае ошибки начинаем цикл сначало | ||
|
|
||
| itemAdd(name, price); | ||
| System.out.println("Вы добавили товар с именем " + name + " и ценой " + price); | ||
| } | ||
|
|
||
| public boolean agreeUser() { // метод на согласие продолжить добавлять товары | ||
| System.out.println("Продолжить добавление товаров (введите Продолжить/Завершить)?:"); | ||
| String agreeUser = scanner.next().toLowerCase(); | ||
| boolean agree = true; | ||
| boolean invalidAgree; | ||
|
|
||
| if (agreeUser.equals("завершить")) { | ||
| agree = false; | ||
| } else if (agreeUser.equals("продолжить")) { | ||
| agree = true; | ||
| } else { | ||
| invalidAgree = true; | ||
| while (invalidAgree) { | ||
| System.out.println("Пожалуйста, выберите ОДНУ из ДОСТУПНЫХ команд: введите Продолжить/Завершить:"); | ||
| agreeUser = scanner.next().toLowerCase(); | ||
|
|
||
| if (agreeUser.equals("завершить")) { | ||
| agree = false; | ||
| invalidAgree = false; | ||
| } else if (agreeUser.equals("продолжить")) { | ||
| agree = true; | ||
| invalidAgree = false; | ||
| } | ||
| } | ||
| } return agree; | ||
|
|
||
| } | ||
|
|
||
|
|
||
| public void total() { // считаем чек с каждого | ||
| System.out.println("Добавленные товары: "); | ||
| for (Item item : items) { | ||
| System.out.println("Товар '" + item.name + "' за " + item.price + " " + rubleFormat(item.price)); | ||
| } | ||
| for (Item item : items) { | ||
| totalPrice = totalPrice + item.price; | ||
| } | ||
| fromEach = (totalPrice / countPeople); | ||
| System.out.println(String.format("Итого, каждый должен заплатить: %.2f ", fromEach) + rubleFormat(fromEach)); | ||
| } | ||
|
|
||
| public String rubleFormat(double price) { // определяем формат слова "рубль" | ||
| int price2 = (int) price; | ||
|
|
||
| rubleFormat = price2 % 10; | ||
| if (rubleFormat == 1) { | ||
| return "рубль"; | ||
| } else if (rubleFormat == 2 || rubleFormat == 3 || rubleFormat == 4) { | ||
| return "рубля"; | ||
| } else { | ||
| return "рублей"; | ||
| } | ||
| } | ||
|
|
||
|
|
||
| public void itemAddMain() { // основная логика калькулятора | ||
| boolean processAdd = true; | ||
| countPeople(); // узнаем количество человек | ||
| boolean agree = true; // пользователь хочет добавить товар | ||
| while (agree) { | ||
| itemAddOut(); // процесс добавления товара | ||
| agree = agreeUser();// узнаем, хочет ли продолжить пользователь | ||
| } if (!agree) { | ||
| total(); // если не хочет, выводим результат | ||
| } | ||
|
|
||
| } | ||
| } | ||
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,5 @@ | ||
| public class Item { | ||
|
|
||
| String name; | ||
| double price; | ||
| } |
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,6 +1,9 @@ | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
| import java.util.Locale; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Перед коммитом стоит приводить файлы к правильному стилю и оптимизировать импорты, так как код будут смотреть другие разработчики. В IDEA это легко делать путём вызова горячей комбинации клавиш (она зависит от ОС), её можно посмотреть в меню Code → Optimize Imports |
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Calc calculator = new Calc(); | ||
| calculator.itemAddMain(); | ||
| } | ||
| } | ||
| } | ||
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.
Можно ещё подумать над более говорящим названием