Repository navigation
Pr1 #19
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
Closed
Closed
Pr1 #19
Changes from all commits
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| public class Calculator { | ||
|
|
||
| int numberOfPeople; | ||
| String currentProduct; | ||
| double currentPrice; | ||
| String productList; | ||
| double allProductPrice; | ||
|
|
||
| Calculator(String productList, double allProductPrice) { | ||
| this.productList = productList; | ||
| this.allProductPrice = allProductPrice; | ||
| } | ||
|
|
||
| void addProductName(String str) { | ||
| this.productList +=str; | ||
| } | ||
|
|
||
| void priceSum(double price) { | ||
| this.allProductPrice += 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,9 +1,103 @@ | ||
| // dev branch for Y.Practicum | ||
| // | ||
| import java.util.Scanner; | ||
| public class Main { | ||
|
|
||
| public static void main(String[] args) { | ||
| // ваш код начнется здесь | ||
| // вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости | ||
| System.out.println("Привет Мир"); | ||
| Calculator calculator = new Calculator("", 0); | ||
|
|
||
| //Запрашиваем количество людей и помещаем в calculator.numberOfPeople. | ||
| System.out.print("На сколько человек разделить счет? "); | ||
| getNumberOfPeople(calculator); | ||
|
|
||
| //Выполняем основной цикл пока isExit() == false | ||
| do { | ||
| System.out.println("Введите название нового товара:"); | ||
| addNewProductName(calculator); | ||
| System.out.println("Введите цену товара в формате \"рубли,копейки\""); | ||
| addNewProductPrice(calculator); | ||
| System.out.printf("Вы добавили товар: %s с ценой %.2f %s\n", calculator.currentProduct, calculator.currentPrice, wordRoubleEnding(calculator.currentPrice)); | ||
| } while (!isExit()); | ||
|
|
||
| //Выводим результат | ||
| printResult(calculator); | ||
| } | ||
|
|
||
| //Метод getNumberOfPeople() запрашивает ввод с консоли значения и помещает его в calculator.numberOfPeople, | ||
| // если значение меньше 1 или не является целым числом, то запрашивает повторно. | ||
| public static void getNumberOfPeople(Calculator calculator) { | ||
| Scanner sc = new Scanner(System.in); | ||
| do { | ||
| System.out.println("Введите целое число больше 1."); | ||
| while (!sc.hasNextInt()) { | ||
| System.out.println("Введите целое число!"); | ||
| sc.next(); | ||
| } | ||
| calculator.numberOfPeople = sc.nextInt(); | ||
| } while (calculator.numberOfPeople <= 1); | ||
| } | ||
|
|
||
| // Метод addNewProductName() запрашивает ввод названия товара и добавляет его в калькулятор | ||
| public static void addNewProductName(Calculator calculator) { | ||
| Scanner sc = new Scanner(System.in); | ||
|
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. scanner можно вынести в тело класса, и там объявить его один раз, а внутри методов уже использовать это поле, |
||
| //Запрашиваем название товара " | ||
| calculator.currentProduct = sc.next(); | ||
| //Добавляем название товара в калькулятор | ||
| calculator.addProductName(calculator.currentProduct + "\n"); | ||
| } | ||
|
|
||
| //Метод addNewProductPrice() запрашивает цену товара и добавляет ее в калькулятор. | ||
| public static void addNewProductPrice(Calculator calculator) { | ||
| Scanner sc = new Scanner(System.in); | ||
| //Запрашиваем цену товара в нужном формате, если формат неверный - выводим ошибку и запрашиваем повторно. | ||
| while (!sc.hasNextDouble()) { | ||
| System.out.println("Неверный формат цены!\nВведите цену товара в формате \"рубли,копейки\""); | ||
| sc.next(); | ||
| } | ||
| //Если формат цены верный, то присваиваем цену calculator.currentPrice и суммируем в калькуляторе. | ||
| calculator.currentPrice = sc.nextDouble(); | ||
| calculator.priceSum(calculator.currentPrice); | ||
| } | ||
|
|
||
| //Метод isExit() возвращает true, если ввели "завершить" иначе возвражает false | ||
| public static boolean isExit() { | ||
| Scanner sc = new Scanner(System.in); | ||
| //Запрашиваем надо ли добавить новый товар или завершить. | ||
| System.out.println("Для добавления нового товара введите любой символ, для завершения введите \"завершить\"."); | ||
| //Если ввели "завершить", то возвращаем true иначе возвращаем false | ||
| return sc.next().equalsIgnoreCase("завершить"); | ||
| } | ||
|
|
||
| //Метод printResult() выводит список товаров, цену на каждого человека, и слово "рубль" с нужным окончанием | ||
| public static void printResult(Calculator calculator) { | ||
| double pricePerPerson = calculator.allProductPrice / calculator.numberOfPeople; | ||
| System.out.print("Добавленные товары:\n" + calculator.productList); | ||
| System.out.printf("Каждый должен заплатить: %.2f %s.\n", pricePerPerson, wordRoubleEnding(pricePerPerson)); | ||
| } | ||
|
|
||
| //Метод wordEnding() возвращает строку с нужным написанием слова "рубль" в зависимости от последних цифр целой части цены. | ||
| public static String wordRoubleEnding(double price) { | ||
| int roundedPrice = (int) Math.floor(price); | ||
| String roubleEnding; | ||
| if (roundedPrice % 100 >= 11 && roundedPrice % 100 <= 19) { | ||
| roubleEnding = "рублей"; | ||
| } else { | ||
| switch (roundedPrice % 10) { | ||
| case 1: | ||
| roubleEnding = "рубль"; | ||
| break; | ||
| case 2: | ||
| case 3: | ||
| case 4: | ||
| roubleEnding = "рубля"; | ||
| break; | ||
| default: | ||
| roubleEnding = "рублей"; | ||
| } | ||
| } | ||
| return roubleEnding; | ||
|
|
||
| } | ||
| } | ||
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.
Лучше не использовать статические методы без необходимости. В данном случае можно было сделать метод не статическим, а внутри статического метода main создать экземпляр класса Main, по аналогии с классом Calculator, и уже у него вызвать методы