From 041a907de932e124c40113f4cc9e606e127185d4 Mon Sep 17 00:00:00 2001 From: harmgehog Date: 2023年12月22日 14:27:10 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B2=D1=8B=D0=B9=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + src/main/java/BillCalc.java | 54 ++++++++++++++++++++++++++ src/main/java/Main.java | 75 ++++++++++++++++++++++++++++++++++++- 3 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 src/main/java/BillCalc.java diff --git a/README.md b/README.md index 63be1bfe0..978d5a2ea 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ # Пустой репозиторий для работы с Java кодом в Android Studio +Первая java программа из андроид студии для практикума. diff --git a/src/main/java/BillCalc.java b/src/main/java/BillCalc.java new file mode 100644 index 000000000..8777ea186 --- /dev/null +++ b/src/main/java/BillCalc.java @@ -0,0 +1,54 @@ +import java.util.ArrayList; +import java.util.List; + +public class BillCalc { + private List items; + private double totalCost; + + public BillCalc() { + items = new ArrayList(); + totalCost = 0; + } + + public void addItem(String itemName, double itemPrice) { + String item = String.format("%s, %.2f", itemName, itemPrice); + items.add(item); + totalCost += itemPrice; + } + + void showTotal() { + System.out.println(totalEnding(totalCost)); + } + + void showByPerson(int persons) { + System.out.println(totalEnding(totalCost / persons)); + } + + void showList() { + for (int i = 0; i < items.size(); i++) { + String[] parts = items.get(i).split(","); + double itemPrice = Double.parseDouble(parts[1].trim()); + + System.out.println((i + 1) + ". " + parts[0].trim() + " - " + totalEnding(itemPrice)); + } + } + + private String totalEnding(double value) { + int rub = (int) value; + int kop = (int) ((value - rub) * 100); + + String endRub; + if (rub % 100> 10 && rub % 100 < 15) endRub = "рублей"; + else if (rub % 10> 1 && rub % 10 < 5) endRub = "рубля"; + else if (rub % 10 == 1) endRub = "рубль"; + else endRub = "рублей"; + + String endKop; + if (kop % 100> 10 && kop % 100 < 15) endKop = "копеек"; + else if (kop % 10> 1 && kop % 10 < 5) endKop = "копейки"; + else if (kop % 10 == 1) endKop = "копейка"; + else endKop = "копеек"; + + return String.format("%d %s %02d %s", rub, endRub, kop, endKop); + } +} diff --git a/src/main/java/Main.java b/src/main/java/Main.java index db9356a08..169abb97d 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,6 +1,79 @@ +import java.util.Scanner; public class Main { + public static int customers = 0; + public static String[] strings = { + "Привет. Это калькулятор счета.", + "Введите кол-во человек:", + "Число должно быть целое и больше 1", + "Завершить", + "Добавленные товары:", + "Товар успешно добавлен в счет", + "Введите название товара (или 'завершить' для выхода): ", + "Название должно содержать только текст (буквы и пробелы)", + "Введите стоимость товара: ", + "Цена не может содержать букв и не должна быть отрицательной", + "Общая сумма счета: ", + "Каждый посетитель должен заплатить: ", + "\nВсе позиции списком: "}; + + static BillCalc calculator = new BillCalc(); + public static void main(String[] args) { - System.out.println("Hello world!"); + + print(0); + customersCount(); + addItems(customers); + } + + public static void customersCount() { + Scanner scanner = new Scanner(System.in); + + while (true) { + print(1); + if (scanner.hasNextInt()) { + customers = scanner.nextInt(); + if (customers> 1) break; + else print(2); + } else print(2); + } + } + + public static void addItems(int persons) { + Scanner scanner = new Scanner(System.in); + + while (true) { + print(6); + String itemName = scanner.next(); + if (!isText(itemName)) { print(7); continue; } + if (itemName.equalsIgnoreCase("завершить")) break; + + print(8); + String itemPrice = scanner.next(); + if (isDouble(itemPrice) && Double.parseDouble(itemPrice)> 0) { + calculator.addItem(itemName, Double.parseDouble(itemPrice)); + print(5); + } else {print(9);} + } + print(10); calculator.showTotal(); + print(11); calculator.showByPerson(persons); + print(12); calculator.showList(); + } + + private static boolean isText(String value) { + return value.matches("[a-zA-Zа-яА-Я ]+"); + } + + private static boolean isDouble(String value) { + try { + Double.parseDouble(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static void print(int arg) { + System.out.println(strings[arg]); } } \ No newline at end of file From dc1f629be78f50f2099df80c83d54644e38cdba5 Mon Sep 17 00:00:00 2001 From: harmgehog Date: 2023年12月23日 14:37:18 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=B2=D1=82=D0=BE=D1=80=D0=BE=D0=B9=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + src/main/java/BillCalc.java | 57 ++++++++++++----------- src/main/java/Main.java | 93 +++++++++++++++++++------------------ 3 files changed, 80 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 978d5a2ea..d5dee5443 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,3 @@ # Пустой репозиторий для работы с Java кодом в Android Studio Первая java программа из андроид студии для практикума. +добавлен второй коммит и второй пулреквест diff --git a/src/main/java/BillCalc.java b/src/main/java/BillCalc.java index 8777ea186..cdf6cea5c 100644 --- a/src/main/java/BillCalc.java +++ b/src/main/java/BillCalc.java @@ -1,41 +1,44 @@ +import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; public class BillCalc { - private List items; - private double totalCost; - - public BillCalc() { - items = new ArrayList(); - totalCost = 0; + private final List items; + private BigDecimal totalCost; + private BigDecimal totalCostPerPerson; + private final BigDecimal persons; + + public BillCalc(int persons) { + this.items = new ArrayList(); + this.totalCost = BigDecimal.valueOf(0.00); + this.totalCostPerPerson = BigDecimal.valueOf(0.00); + this.persons = BigDecimal.valueOf(persons); } - public void addItem(String itemName, double itemPrice) { - String item = String.format("%s, %.2f", itemName, itemPrice); + public void addItem(String itemName, String price) { + BigDecimal itemPrice = new BigDecimal(price.trim()).setScale(2, RoundingMode.HALF_UP); + String item = itemName + ", " + itemPrice; items.add(item); - totalCost += itemPrice; - } - - void showTotal() { - System.out.println(totalEnding(totalCost)); + totalCost = totalCost.add(itemPrice); + totalCostPerPerson = totalCost.divide(persons, RoundingMode.HALF_UP); } - void showByPerson(int persons) { - System.out.println(totalEnding(totalCost / persons)); - } - - void showList() { + public void printTotal() { + System.out.println("Количество посетителей: " + persons.setScale(0, RoundingMode.DOWN)); + System.out.println("Общая сумма счета: " + totalEnding(totalCost)); + System.out.println("Каждый посетитель должен заплатить: " + totalEnding(totalCostPerPerson)); + System.out.println("\nВсе позиции меню: "); for (int i = 0; i < items.size(); i++) { - String[] parts = items.get(i).split(","); - double itemPrice = Double.parseDouble(parts[1].trim()); - - System.out.println((i + 1) + ". " + parts[0].trim() + " - " + totalEnding(itemPrice)); + String name = items.get(i).split(",")[0]; + BigDecimal price = new BigDecimal(items.get(i).split(", ")[1]); + System.out.println((i+1) + ". " + name + " - " + totalEnding(price)); } } - private String totalEnding(double value) { - int rub = (int) value; - int kop = (int) ((value - rub) * 100); + private String totalEnding(BigDecimal val) { + double rub = val.setScale(0, RoundingMode.DOWN).doubleValue(); + double kop = val.multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.DOWN).doubleValue() % 100; String endRub; if (rub % 100> 10 && rub % 100 < 15) endRub = "рублей"; @@ -44,11 +47,11 @@ private String totalEnding(double value) { else endRub = "рублей"; String endKop; - if (kop % 100> 10 && kop % 100 < 15) endKop = "копеек"; + if (kop> 10 && kop < 15) endKop = "копеек"; else if (kop % 10> 1 && kop % 10 < 5) endKop = "копейки"; else if (kop % 10 == 1) endKop = "копейка"; else endKop = "копеек"; - return String.format("%d %s %02d %s", rub, endRub, kop, endKop); + return String.format("%.0f %s %.0f %s", rub, endRub, kop, endKop); } } diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 169abb97d..868aef06c 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -4,76 +4,81 @@ public class Main { public static int customers = 0; public static String[] strings = { "Привет. Это калькулятор счета.", - "Введите кол-во человек:", - "Число должно быть целое и больше 1", - "Завершить", - "Добавленные товары:", + "Введите КОЛ-ВО человек (или 'завершить' для выхода):", + "Неверно: Должно быть целое число. 1 < ЧИСЛО < 1000", "Товар успешно добавлен в счет", - "Введите название товара (или 'завершить' для выхода): ", - "Название должно содержать только текст (буквы и пробелы)", - "Введите стоимость товара: ", - "Цена не может содержать букв и не должна быть отрицательной", - "Общая сумма счета: ", - "Каждый посетитель должен заплатить: ", - "\nВсе позиции списком: "}; + "Введите НАЗВАНИЕ товара (или 'завершить' для выхода): ", + "Неверно: Название должно содержать текст (буквы, цифры, некоторые знаки препинания, кроме запятой)", + "Введите СТОИМОСТЬ товара (или 'завершить' для выхода): ", + "Неверно: 0.00 <= ЦЕНА < 150000000.00,\n Цена, это число не более 2х знаков после запятой."}; - static BillCalc calculator = new BillCalc(); + static BillCalc calculator; public static void main(String[] args) { + printString(0); - print(0); - customersCount(); - addItems(customers); + if (customersCount()) return; + calculator = new BillCalc(customers); + addItems(); + calculator.printTotal(); } - public static void customersCount() { + public static boolean customersCount() { Scanner scanner = new Scanner(System.in); while (true) { - print(1); - if (scanner.hasNextInt()) { - customers = scanner.nextInt(); - if (customers> 1) break; - else print(2); - } else print(2); + printString(1); + String input = scanner.nextLine(); + if (input.trim().equalsIgnoreCase("завершить")) return true; + try { + customers = Integer.parseInt(input); + if (customers> 1 && customers < 1000) break; + } catch (NumberFormatException ignored) {} + printString(2); } + return false; } - public static void addItems(int persons) { + public static void addItems() { Scanner scanner = new Scanner(System.in); - - while (true) { - print(6); - String itemName = scanner.next(); - if (!isText(itemName)) { print(7); continue; } - if (itemName.equalsIgnoreCase("завершить")) break; - - print(8); - String itemPrice = scanner.next(); - if (isDouble(itemPrice) && Double.parseDouble(itemPrice)> 0) { - calculator.addItem(itemName, Double.parseDouble(itemPrice)); - print(5); - } else {print(9);} + boolean flag = true; + while (flag) { + printString(4); + String itemName = scanner.nextLine(); + if (itemName.trim().equalsIgnoreCase("завершить")) flag = false; + else if (!isText(itemName)) { + printString(5); + continue; + } + while(flag) { + printString(6); + String itemPrice = scanner.nextLine(); + if (itemPrice.trim().equalsIgnoreCase("завершить")) flag = false; + else if (isPrice(itemPrice)) { + calculator.addItem(itemName, itemPrice); + printString(3); + break; + } + else printString(7); + } } - print(10); calculator.showTotal(); - print(11); calculator.showByPerson(persons); - print(12); calculator.showList(); } private static boolean isText(String value) { - return value.matches("[a-zA-Zа-яА-Я ]+"); + return value.matches("[a-zA-Zа-яА-Я\\d\\p{Punct} &&[^,]]+"); } - private static boolean isDouble(String value) { + private static boolean isPrice(String value) { try { - Double.parseDouble(value); - return true; + double number = Double.parseDouble(value); + int decimalPlaces = value.indexOf('.')>= 0 ? value.length() - value.indexOf('.') - 1 : 0; + return number>= 0 && number < 150000000.00 && decimalPlaces <= 2; } catch (NumberFormatException e) { return false; } } - public static void print(int arg) { + public static void printString(int arg) { System.out.println(strings[arg]); } } \ No newline at end of file

AltStyle によって変換されたページ (->オリジナル) /