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

Pull request for extraction with my project work #2

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
DexMP wants to merge 9 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
96 changes: 95 additions & 1 deletion src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,100 @@
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");

// List
ArrayList<Product> productsName = new ArrayList<Product>();

// Переменные
int humans;
double price;
String products;
float summ = 0;

// Сканеры
Scanner scanner_humans = new Scanner(System.in);
Copy link

@kgornostaeva kgornostaeva Oct 25, 2023

Choose a reason for hiding this comment

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

🍏 В Java принято переменные писать в camelCase, а названия классов CamelCase.
SNAKE_CASE используется для именования констант, а snake_case - для именования xml файлов.
https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html

Scanner scanner_products = new Scanner(System.in);
Scanner scanner_prices = new Scanner(System.in);

Comment on lines +17 to +20
Copy link

@kgornostaeva kgornostaeva Oct 25, 2023

Choose a reason for hiding this comment

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

🍏 Для всего взаимодействия с пользователем достаточно открыть один сканнер

// Поздороваемся!
System.out.println("Доброго времени суток!\n" +
"На скольких человек необходимо разделить счёт:");

// Получаем количество людей
while (true) {
if (scanner_humans.hasNextInt()) {
Copy link

@kgornostaeva kgornostaeva Oct 25, 2023

Choose a reason for hiding this comment

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

👏 Круто, что делаешь проверку на наличие числа

DexMP reacted with heart emoji
humans = scanner_humans.nextInt();
while (humans <= 1) {
System.out.println("Количество людей должно быть более 1");
humans = scanner_humans.nextInt();
if (humans > 1) break;
}
break;
} else {
System.out.println("Возможно вы ввели не число, попробуйте ещё раз!");
scanner_humans.nextLine();
}
}

// Получаем товары
while (true) {
System.out.println("Название товара:");
if (scanner_products.hasNext()) {
products = scanner_products.nextLine();
if (!products.equalsIgnoreCase("завершить")) {
productsName.add(new Product(products));
System.out.println("Укажите цену товара в формате рубли.копейки: ");
if (scanner_prices.hasNextDouble()) {
price = scanner_prices.nextDouble();
while (price <= 0) {
System.out.println("Значение не может быть 0 или меньше!");
price = scanner_prices.nextDouble();
if (price > 0) {
System.out.println(String.format("Цена: %.2f", price));
break;
}
}
summ += price;
System.out.println("Добавленные товары:");
for (Product name : productsName) {
System.out.println("* " + productsName.get(i).productName);
}
System.out.println("Сумма: " + String.format("%.2f", summ));
} else {
System.out.println("Кажется вы указали неверный формат!");
scanner_prices.hasNextDouble();
}
} else {
float forPerson = summ / humans;
int rubles = (int) forPerson;

System.out.println("Сумма на каждого человека " + String.format("%.2f", forPerson) + " " + grammar(rubles));
Copy link

@kgornostaeva kgornostaeva Oct 25, 2023

Choose a reason for hiding this comment

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

🍏 При печати в памяти будут создаваться промежуточные строки из-за множественного использования оператора "+". Можно использовать StringBuilder, который сформирует только результирующую строку, или String.format()

break;
}
} else {
System.out.println("Не получено данных о товаре!");
scanner_products.nextLine();
}
}
}

private static String grammar(int rubles) {
if (lastIndexRub(rubles).equals("0")) {
return "рублей";
} else if (lastIndexRub(rubles).equals("1")) {
return "рубль";
} else if (lastIndexRub(rubles).equals("2") || lastIndexRub(rubles).equals("3") || lastIndexRub(rubles).equals("4")) {
return "рубля";
} else {
return "рублей";
}
}

private static String lastIndexRub(int rubles) {
String str = String.valueOf(rubles);
str.substring(str.length() - 1);
return str;
}
}
8 changes: 8 additions & 0 deletions src/main/java/Product.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
public class Product {

String productName;

public Product(String productName) {
this.productName = productName;
}
}

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