Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Практическая работа No1 #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
Venser724 wants to merge 7 commits into main
base: main
Choose a base branch
Loading
from dev
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# Пустой репозиторий для работы с Java кодом в Android Studio
# Уже не пустой репозиторий для работы с Java кодом в Android Studio
11 changes: 11 additions & 0 deletions src/main/java/Calculator.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import java.util.ArrayList;

public class Calculator {
static float calculate(ArrayList<Good> receipt, int numberOfGuests) {
float totalPrice = 0;
for (Good good : receipt) {
totalPrice += good.price;
}
return totalPrice / numberOfGuests;
}
}
29 changes: 29 additions & 0 deletions src/main/java/Formatter.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.util.ArrayList;

public class Formatter {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здорово, что форматтер вынесен в отдельный класс!


static String getFormattedOutput(float price) {
int resultInt = (int) price;

String rubles;
if (resultInt % 100 <= 19 && resultInt % 100 >= 11) {
rubles = "рублей";
} else if (resultInt % 10 >= 2 && resultInt % 10 <= 4) {
rubles = "рубля";
} else if (resultInt % 10 == 1) {
rubles = "рубль";
} else {
rubles = "рублей";
}
return String.format("С каждого по %.2f %s", price, rubles);
}

static String getFormattedGoods(ArrayList<Good> goods) {
StringBuilder result = new StringBuilder();
result.append("Добавленные товары:\n");
for (Good good : goods) {
result.append(good.name).append('\n');
}
return result.toString().trim();
}
}
9 changes: 9 additions & 0 deletions src/main/java/Good.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Good {
float price;
String name;

public Good(float price, String name) {
this.price = price;
this.name = name;
}
}
106 changes: 104 additions & 2 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,108 @@
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
private final static String GREET = "На сколько человек требуется разделить счёт?";
private final static String ERROR_INCORRECT_NUMBER = "Введено некорректное число. \nВведите корректное число.";
private final static String ADD_NEW_GOOD = "Добавление товара. Ведите наименование товара или 'Завершить' для перехода к расчёту чека";

public static void main(String[] args) {
System.out.println("Hello world!");
ArrayList<Good> receipt = new ArrayList<>();


System.out.println(GREET);
int number = 1;
Scanner scanner = new Scanner(System.in);
//int number = inputNumber(scanner);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень хорошо коммитить закоментированный код


while (number <= 1) {
try {
number = inputNumber(scanner);
if (number <= 1) {
System.out.println(ERROR_INCORRECT_NUMBER);
}
} catch (Exception e) {
System.out.println(ERROR_INCORRECT_NUMBER);
}
}


System.out.println(ADD_NEW_GOOD);
String name = scanner.nextLine();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь есть небольшое повторение. Мы выводим строку перед циклом и в конце цикла. Можно использовать цикл do-while, чтобы этого избежать(Но это совсем не обязательно!).

while (!name.equalsIgnoreCase("завершить")) {
System.out.println("Введите цену товара:");
float price = -1;

while (price < 0) {

try {
price = inputFloat(scanner);
} catch (Exception exception) {
System.out.println(ERROR_INCORRECT_NUMBER);
}
}

Good good = new Good(price, name);
receipt.add(good);
System.out.println(ADD_NEW_GOOD);
name = scanner.nextLine();

}
float result = Calculator.calculate(receipt, number);
System.out.println(Formatter.getFormattedGoods(receipt));
System.out.println(Formatter.getFormattedOutput(result));
}

static boolean checkForInt(String string) {
boolean isWasMinus = false;
for (int i = 0; i < string.length(); ++i) {
if (!Character.isDigit(string.charAt(i))) {
if (!Character.isDigit(string.charAt(i))) {
Comment on lines +59 to +60
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем тут два раза одинаковая проверка?

if (string.charAt(i) == '-' && !isWasMinus) {
isWasMinus = true;
} else {
return false;
}
}
}
}
return true;
}

static int inputNumber(Scanner scanner) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне нравится, что логика вынесена в отдельные функции, но кажется, что можно было сделать проще используюя стандартные методы сканера.

String numberOfGuests = scanner.nextLine();
while (!checkForInt(numberOfGuests)) {
System.out.println(ERROR_INCORRECT_NUMBER);
numberOfGuests = scanner.nextLine();

}
return Integer.parseInt(numberOfGuests);
}

static boolean checkForFloat(String string) {
boolean isWasDot = false;
boolean isWasMinus = false;
for (int i = 0; i < string.length(); ++i) {
if (!Character.isDigit(string.charAt(i))) {
if (string.charAt(i) == '-' && !isWasMinus) {
isWasMinus = true;
} else if (string.charAt(i) == '.' && !isWasDot) {
isWasDot = true;
} else {
return false;
}
}
}
return true;
}

static float inputFloat(Scanner scanner) {
String numberOfGuests = scanner.nextLine();
while (!checkForFloat(numberOfGuests)) {
System.out.println(ERROR_INCORRECT_NUMBER);
numberOfGuests = scanner.nextLine();

}
return Float.parseFloat(numberOfGuests);
}
}
}

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