Repository navigation
Финальная версия консольного приложения #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
base: main
Are you sure you want to change the base?
Changes from all commits
750a666
e56290c
1bdec04
67d5238
08688fe
e38570a
a7586ea
f4b98d4
9a719e9
e6013d5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,11 @@ | ||
| # Пустой репозиторий для работы с Java кодом в Android Studio | ||
| # Перед вами исходный код консольного приложения ___"Побратски попилим счет, а?"___. | ||
| ## Devoloper: __Stepan Groshev__ | ||
| ___ | ||
| Главной задачей, которую решает данное приложение, является распил суммы братского счёта на количество братюнь. | ||
| Братюня, который активирует приложение, изначально должен ввести количество братюнь, на которых необходимо попилить счёт. | ||
| Дальше, с помощью приложения, написанного начинающим __дЭвЭлопЭром__, он формирует список позиций братского счёта, указывая | ||
| наименоване каждой позиций и её стоимость. Когда список сформирован, приложение производит алгебраический расчет, на который | ||
| братюня сам неспособен, но способен алгоритм и золотые пальцы __дЭвЭлопЭра__, сообщая ему сколько каждый из его братюнь, | ||
| включая его самого, должен скинуть в общаг, чтоб расплатиться в заведении, в котором они только что культурно отдыхали, | ||
| я надеюсь, что культурно, братиш ;) | ||
| ___ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import java.util.ArrayList; | ||
|
|
||
| public class Calculate { | ||
| Double sum = 0.0; | ||
| ArrayList<Product> listProduct = new ArrayList<Product>(); | ||
| Formatter formatter = new Formatter(); | ||
| void sum (Double costProduct){ | ||
| sum = sum + costProduct; | ||
| } | ||
| void addingProductsToCalculate(Product product){ | ||
| listProduct.add(product); | ||
| } | ||
| double division(Double sum, int numberOfPerson){ | ||
| return sum / numberOfPerson; | ||
| } | ||
|
|
||
| void addingProductsToConsole(){ | ||
| for (int i = 0; i < listProduct.size(); i++ ){ | ||
| String text = String.format("%d-я позиция по счету: %s - стоимость которой = %.2f %s", i | ||
| + 1, listProduct.get(i).nameProduct,listProduct.get(i).costProduct, formatter.formatter(listProduct.get(i).costProduct)); | ||
| System.out.println(text); | ||
| } | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| public class Formatter { | ||
|
|
||
| String formatter(Double value){ | ||
| String str = ""; | ||
| int a = roundingUp(value); | ||
|
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. переменным нужно стараться присваивать говорящие, а не абстрактные имена :) |
||
| int val = String.valueOf(a).length(); | ||
|
|
||
| while(true) { | ||
|
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. кажется, что этот цикл здесь совсем не обязателен - его можно удалить |
||
| switch (val) { | ||
| case 0: { | ||
| str = "рублей"; | ||
|
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. слово
|
||
| break; | ||
| } | ||
| case 1: { | ||
| str = decimalConversion(a, str); | ||
| break; | ||
| } | ||
| case 2: { | ||
| str = hundredthsConverting(a, str); | ||
| break; | ||
| } | ||
| default: | ||
| a = a % 100; | ||
| str = hundredthsConverting(a, str); | ||
| break; | ||
| } | ||
| return str; | ||
| } | ||
| } | ||
|
|
||
| int roundingUp (Double value){ | ||
| return (int) Math.floor(value); | ||
| } | ||
|
|
||
| String decimalConversion (int a, String str){ | ||
| if (a == 1) { | ||
| str = "рубль"; | ||
| } else if (a != 1 && a > 0 && a <= 4) { | ||
| str = "рубля"; | ||
| } else if (a == 0 || a == 5 || a == 6 || a == 7 || a == 8 || a == 9) { | ||
| str = "рублей"; | ||
| } | ||
| return str; | ||
| } | ||
|
|
||
| String hundredthsConverting (int a, String str){ | ||
| if (a == 11 || a == 12 || a == 13 || a == 14) { | ||
| str = "рублей"; | ||
| return str; | ||
| } | ||
| a = a % 10; | ||
| str = decimalConversion(a,str); | ||
| return str; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,106 @@ | ||
| import java.util.Locale; | ||
| 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 numberOfPerson; | ||
| int countWhile = 0; | ||
| int countProduct = 0; | ||
|
|
||
| System.out.println("Вас приветствует консольное приложение \"Побратски попилим счет, а?\".\n" + | ||
| "На скольких братюнь необходимо попилить ваш счёт?\nВведите числовое значение >1 ..."); | ||
|
|
||
| numberOfPerson = checkingUserInputString(); | ||
| checkingUserInputOfTaskCondition(numberOfPerson); | ||
| Calculate calculate = new Calculate(); | ||
| Formatter formatter = new Formatter(); | ||
|
|
||
| while (true) { | ||
| System.out.println("Вы хотите добавить позицию из счета? \n" + | ||
| "(Введите: \"да\" - если хотите ее добавить; \"завершить\" - если не хотите добавлять)..."); | ||
| String userInput = scanner.next().toLowerCase(Locale.ROOT); | ||
| switch (userInput) { | ||
| case "да": { | ||
| System.out.println("Введите наименование позиции из счета..."); | ||
| String nameProduct = scanner.next(); | ||
| System.out.println("Введите стоимость позиции из счета..."); | ||
| double costProduct = checkingUserInputDouble(); | ||
| checkingValueProduct(costProduct); | ||
| Product product = new Product(nameProduct, costProduct); | ||
| calculate.addingProductsToCalculate(product); | ||
| calculate.sum(costProduct); | ||
| countProduct++; | ||
| break; | ||
| } | ||
| case "завершить": { | ||
| countWhile++; | ||
| System.out.println("Ввод позиций по счету успешно завершен.\n" + | ||
| "Количество добавленных позиций = " + countProduct +".\n\nДобавленные позиции:"); | ||
| calculate.addingProductsToConsole(); | ||
| break; | ||
| } | ||
| default: | ||
| System.out.println("Вы ввели некорректное значение, повторите попытку..."); | ||
| }if (countWhile == 1){ | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| double division = calculate.division(calculate.sum, numberOfPerson); | ||
| if (calculate.sum == 0){ | ||
| System.out.println("\nПозицици счета не были добавлены, нечего пилить. Завершение программы, братиш ;)"); | ||
| }else { | ||
| String outputText = String.format("\nОбщая стоимость всех позиций братского счета = %.2f %s\n" + | ||
| "Количество братюнь, на которых необходимо попилить счет = %d\n" + | ||
| "Каждый братюня должен скинуть по - %.2f %s", calculate.sum, formatter.formatter(calculate.sum), | ||
| numberOfPerson, division, formatter.formatter(division)); | ||
| System.out.println(outputText); | ||
| } | ||
| } | ||
| static int checkingUserInputString (){ | ||
| Scanner scanner = 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. не нужно создавать много сканнеров - достаточно одного экземпляра этого класса
|
||
| while (!scanner.hasNextInt()) { | ||
| System.out.println("Введите корректное значение, целое число больше 1-ого ..."); | ||
| scanner.nextLine(); | ||
| }return scanner.nextInt(); | ||
| } | ||
|
|
||
| static int checkingUserInputOfTaskCondition(int number){ | ||
| Scanner scanner = new Scanner(System.in); | ||
| while (true) { | ||
| if (number == 1) { | ||
| System.out.println("Введите значение >1..."); | ||
| number = checkingUserInputString(); | ||
| } else if (number > 1) { | ||
| System.out.println("Введено корректное значение количества братюнь, молодец братиш ;)"); | ||
| break; | ||
| } else if (number <= 0) { | ||
| System.out.println("Введено значение ноль или меньше нуля, повторите попытку..."); | ||
| number = checkingUserInputString(); | ||
| } | ||
| }return number; | ||
| } | ||
|
|
||
| static double checkingUserInputDouble(){ | ||
| Scanner scanner = new Scanner(System.in); | ||
| while(!scanner.hasNextDouble()) { | ||
| System.out.println("Необходимо ввести ЧИСЛОВОЕ значение стоимости позиции из счета, повторите попытку..."); | ||
| scanner.nextLine(); | ||
| }return scanner.nextDouble(); | ||
|
|
||
| } | ||
|
|
||
| static double checkingValueProduct(double costProduct){ | ||
| while (true) { | ||
| if (costProduct <= 0) { | ||
| System.out.println("Введено значение ноль или меньше нуля, повторите попытку..."); | ||
| costProduct = checkingUserInputDouble(); | ||
| }else if (costProduct > 0){ | ||
| System.out.println( "Введено корректное значение стоимости позиции из счета, молодец братиш ;)"); | ||
| break; | ||
| } | ||
| }return costProduct; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| public class Product { | ||
| String nameProduct = "name"; | ||
|
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. значение |
||
| Double costProduct; | ||
|
|
||
| Product(String nameProduct, Double costProduct){ | ||
| this.nameProduct = nameProduct; | ||
| this.costProduct = costProduct; | ||
| } | ||
| } | ||
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.
довольно громоздкая конструкция для восприятия. для удобочитаемости можно вынести подставляемые значения в отдельные переменные, либо воспользоваться
StringBuilderом