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
A2T-user
wants to merge
4
commits into
main
Choose a base branch
from
dev
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
4 commits
Select commit
Hold shift + click to select a range
1923475
Андрей Трофимов консольное приложение №1
A2T-user 27d5a1a
Андрей Трофимов Консольное приложение №1. Версия 2.0
A2T-user afa1b3a
Андрей Трофимов Консольное приложение №1. Версия 3.0
A2T-user 76321e3
Андрей Трофимов Консольное приложение №1. Версия 4.0
A2T-user 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,88 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
|
|
||
| public class DataInput { | ||
| // Ввод кол-ва человек | ||
| public int numberOfPeople (Scanner scanner) { | ||
| int numberOfPersons; | ||
| final String STR_QUERY = "На сколько человек необходимо разделить счёт:"; | ||
| final String STR_NOTE = "\nВведите целое число больше 1."; | ||
| do { | ||
| System.out.println(STR_QUERY); | ||
| while (!scanner.hasNextInt()) { | ||
| System.out.println(new StringBuilder().append("Это не целое число!").append(STR_NOTE).append("\n").append(STR_QUERY)); | ||
| scanner.next(); | ||
| } | ||
| numberOfPersons = scanner.nextInt(); | ||
| if (numberOfPersons < 0) { | ||
| System.out.println(new StringBuilder().append("Это отрицательное число!").append(STR_NOTE)); | ||
| } else if (numberOfPersons == 0) { | ||
| System.out.println(new StringBuilder().append("На 0 делить нельзя!").append(STR_NOTE)); | ||
| } else if (numberOfPersons == 1) { | ||
| System.out.println(new StringBuilder().append("Нет смысла делить. Весь счет оплачивать Вам!").append(STR_NOTE)); | ||
| } | ||
| } while (numberOfPersons <= 1); | ||
| return numberOfPersons; | ||
| } | ||
|
|
||
| // Ввод товара | ||
| public ArrayList<Product> productEntry (Scanner scanner) { | ||
| final String STR_END_INPUT = "Завершить"; // Кодовое слово для завершения ввода | ||
|
|
||
| ArrayList<Product> listOfProducts = new ArrayList<>(); // Массив для хранения содержимого строк счета | ||
| do { | ||
| String name; | ||
| float price; | ||
| boolean empty; | ||
| do { | ||
| // Ввод наименования товара | ||
| System.out.println("Введите наименование товара:"); | ||
| name = scanner.next(); | ||
| // Проверка, что строка не пустая. Кажется она не требуется (при пустой строке scanner будет повторять запрос на ввод), но на всякий случай | ||
| empty = name.isEmpty(); | ||
| if (empty) { | ||
| System.out.println("У товара должно быть наименование, пустые строки не допускаются!"); | ||
| } | ||
| } while (empty); | ||
| // Ввод и проверка цены | ||
| price = enteringAndCheckingPrices(scanner); | ||
| Product lb = new Product(name, price); // Создание объекта для хранения данных строки счета | ||
| listOfProducts.add(lb); // и добавление его в массив | ||
| System.out.println("Товар успешно добавлен."); | ||
| System.out.println("Хотите добавить еще один товар?\nДля завершения процесса добавления товаров введите \"Завершить\":"); | ||
| } while (!scanner.next().equalsIgnoreCase(STR_END_INPUT)); | ||
| return listOfProducts; | ||
| } | ||
|
|
||
| // Ввод и проверка цены | ||
| private float enteringAndCheckingPrices (Scanner scanner) { | ||
| final int DIGITS_AFTER_DOT = 2; // Максимальное кол-во цифр после десятичной точки | ||
|
|
||
| float price; | ||
| String s = "\nОжидается число больше 0 в формате \"0.00\"."; | ||
| String s1 = "Введите стоимость товара:"; | ||
|
|
||
| do { | ||
| System.out.println(s1); | ||
| // Проверка случайных символов | ||
| while (!scanner.hasNextDouble()) { | ||
| System.out.println("Это вообще не число!" + s + "\n" + s1); | ||
| scanner.next(); | ||
| } | ||
| price = scanner.nextFloat(); | ||
| // Проверка: цена > 0 | ||
| if (price == 0) { | ||
| System.out.println("Бесплатный товар? Хмм..." + s); | ||
| } else if (price <= 0) { | ||
| System.out.println("Ого! Вы где нашли такие цены?" + s); | ||
| } | ||
| // Проверка - у цены должно быть две цифры после десятичной точки | ||
| String[] strPrice = String.valueOf(price).split("\\.", 2); // Разбиваем строку на массив из 2-х строк: целая часть и дробная | ||
| if (strPrice[1].length() > DIGITS_AFTER_DOT) { // Если в дробной части больше 2 знаков | ||
| System.out.println("Многовато копеек!" + s); | ||
| price = 0.0f; | ||
| } | ||
| } while (price <= 0); | ||
| return 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 |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class DataOutput { | ||
| // Вывод итогов | ||
| public void outputOfResults (int numberOfPersons, ArrayList<Product> listOfProducts) { | ||
| float sumBill = 0; | ||
| System.out.println("Добавленные товары:\n"); // Заголовок | ||
| for (Product item : listOfProducts) { | ||
| float prise = item.getPrise(); | ||
| sumBill = sumBill + prise; | ||
| System.out.printf("%s ..... %.2f%n", item.getName(), prise); | ||
| } | ||
| System.out.printf("---------------------" + "Итого по счету: %.2f\n%n", sumBill); // Подчеркивание и вывод итоговой суммы по счету | ||
| double fromEveryPerson = sumBill / numberOfPersons; | ||
| System.out.printf("\nГоспода, с Вас по: %.2f %s%n", fromEveryPerson, rubles(fromEveryPerson)); // Вывод доли счета | ||
| } | ||
|
|
||
| // Правильное окончание слова "рубль" | ||
| private String rubles (double fromEveryPerson) { | ||
| int lastDigit = ((int) fromEveryPerson) % 10; // Получаем последнюю цифру целой части | ||
| String s; | ||
| if (lastDigit == 0) { | ||
| s = "рублей"; | ||
| } else if (lastDigit == 1) { | ||
| s = "рубль"; | ||
| } else if (lastDigit < 5) { | ||
| s = "рубля"; | ||
| } else { | ||
| s = "рублей"; | ||
| } | ||
| return s; | ||
| } | ||
| } |
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,17 @@ | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
| Scanner scanner = new Scanner(System.in); | ||
| DataInput dataInput = new DataInput(); | ||
| // Запрос кол-ва участников | ||
| int numberOfPersons = dataInput.numberOfPeople(scanner); | ||
| // Ввод товара | ||
| ArrayList<Product> listOfProducts = dataInput.productEntry(scanner); | ||
| scanner.close(); // Закрыть сканер | ||
| // Вывод счета, итога и причетающейся каждому суммы | ||
| new DataOutput().outputOfResults(numberOfPersons, listOfProducts); | ||
| } | ||
| } | ||
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,11 @@ | ||
| public class Product { | ||
| private String name; | ||
| private float price; | ||
|
|
||
| public Product(String name, float price) { | ||
| this.name = name; | ||
| this.price = price; | ||
| } | ||
| public String getName() { return name; } | ||
| public float getPrise() { return price; } | ||
| } |
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.
👏 Круто, что не забываешь завершить работу со сканнером
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.
Спасибо