Repository navigation
Проектная работа №1 (спринт 2) Калькулятор #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
DoNatPanic
wants to merge
1
commit 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
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 |
|---|---|---|
| @@ -1 +1,4 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
|
|
||
| Реализован калькулятор: | ||
| все заказанные товары складываются в общий счет, который делится поровну между всеми участниками компании. |
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,55 @@ | ||
| import java.util.ArrayList; | ||
| import java.util.Scanner; | ||
|
|
||
| public class Calculator { | ||
| public int personCount; | ||
| public double totalPriceSum; | ||
| public double dividedSum; | ||
| public ArrayList<Product> products = new ArrayList<>(); | ||
| private final Scanner scanner = new Scanner(System.in); | ||
|
|
||
| Calculator(int personCount){ | ||
| this.personCount = personCount; | ||
| } | ||
| public void addToCart(){ | ||
| while (true) { | ||
| System.out.println("\nВведите название товара:"); | ||
| String inputName = scanner.nextLine(); | ||
| if(inputName.trim().equalsIgnoreCase("завершить")) { | ||
| break; | ||
| } | ||
|
|
||
| System.out.println("Введите его стоимость в формате 'рубли.копейки':"); | ||
| while (true) { | ||
| String inputPrice = scanner.nextLine(); | ||
| try | ||
| { | ||
| double price = Double.parseDouble(inputPrice); | ||
| if(price < 0) { | ||
| System.out.println("Стоимость не может быть отрицательной. Повторите ввод:"); | ||
| } else { | ||
| System.out.printf("Принято: товар '%s' с ценой %.2f успешно добавлен в корзину!%n", inputName, price); | ||
| totalPriceSum += price; | ||
| products.add(new Product(inputName, price)); | ||
| System.out.println("Если хотите добавить еще товары, продолжайте ввод, иначе введите 'Завершить'"); | ||
| break; | ||
| } | ||
| } | ||
| catch (NumberFormatException e) | ||
| { | ||
| System.out.println("Неверный формат: введите стоимость товара в формате 'рубли.копейки':"); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public String calculate() { | ||
| dividedSum = totalPriceSum / personCount; | ||
|
|
||
| // определяем, с каким окончанием нужно закончить фразу: "рубль/рубля/рублей" | ||
| Formatter formatter = new Formatter(); | ||
| String phraseEnd = formatter.getPhraseEnd(dividedSum); | ||
|
|
||
| return String.format("Все должны заплатить по %.2f %s", dividedSum, phraseEnd); | ||
| } | ||
| } | ||
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,9 @@ | ||
| public class Formatter { | ||
| public String getPhraseEnd(double dividedSum) { | ||
| return switch ((int) dividedSum % 10) { | ||
| case 1 -> "рубль"; | ||
| case 2, 3, 4 -> "рубля"; | ||
| default -> "рублей"; | ||
| }; | ||
| } | ||
| } |
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,49 @@ | ||
| import java.util.Scanner; | ||
|
|
||
| public class Main { | ||
| public static void main(String[] args) { | ||
| System.out.println("Hello world!"); | ||
|
|
||
| Scanner scanner = new Scanner(System.in); | ||
|
|
||
| // количество гостей | ||
| int personCount; | ||
|
|
||
| // 1. Входные параметры для счётчика | ||
| while (true) { | ||
| System.out.println("На скольких человек необходимо разделить счёт?"); | ||
| String input = scanner.nextLine(); | ||
|
|
||
| try | ||
| { | ||
| personCount = Integer.parseInt(input); | ||
| if(personCount == 1) { | ||
| System.out.println("Счет делить не требуется. Завершаем программу"); | ||
| return; | ||
| } else if(personCount < 1) { | ||
| System.out.println("Неверный формат: введите положительное число"); | ||
| } else { | ||
| System.out.println("Принято: количество человек: " + personCount); | ||
| break; | ||
| } | ||
| } | ||
| catch (NumberFormatException e) | ||
| { | ||
| System.out.println("Неверный формат: введите целое число."); | ||
| } | ||
| } | ||
|
|
||
| // создание калькулятора | ||
| Calculator calculator = new Calculator(personCount); | ||
|
|
||
| // 2. Добавление товаров в калькулятор | ||
| calculator.addToCart(); | ||
|
|
||
| System.out.println("Добавленные товары:"); | ||
| for(Product product : calculator.products){ | ||
| System.out.printf("%s %.2f%n", product.name, product.price); | ||
| } | ||
|
|
||
| // 3. Расчет и вывод результата | ||
| System.out.println(calculator.calculate()); | ||
| } | ||
| } |
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,9 @@ | ||
| public class Product { | ||
| String name; | ||
| double price; | ||
|
|
||
| public Product(String name, double price) { | ||
| this.name = name; | ||
| this.price = 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.
а как тогда можно написать чтобы не возникло исключения при парсинге в тип double?
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.
то есть если пользователь ввел буквы, вместо числа, то программа упадет, если не обернуть в блок try catch
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.
можно сделать, например, как здесь https://github.com/DetroitRW/Java-Module-Project-YP/blob/dev/src/main/java/Main.java (методы readDouble(), readPrice())
в начале проверяем, что введен double, потом проверяем на условие >2 и если не подходит, то снова запрашиваем double
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.
поподробнее почему так нельзя делать можно почитать в книге Java: Эффективное программирование Джошуа Блох глава 10.1. Используйте исключения только в исключительных ситуациях
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.
Спасибо за информацию) обязательно ознакомлюсь