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. PR #112

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
AugustIva wants to merge 4 commits into Yandex-Practicum:master
base: master
Choose a base branch
Loading
from AugustIva:master
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
12 changes: 8 additions & 4 deletions src/main/java/Main.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
public class Main {
public abstract class Main {
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Abstract у Main можно убрать. Дальше по курсу будет рассказано, что это такое, но пока не нужно



public static void main(String[] args) {
// ваш код начнется здесь
// вы не должны ограничиваться только классом Main и можете создавать свои классы по необходимости
System.out.println("Привет Мир");
ProductsList.menuChoice();
ProductsList.debt();
}
}




135 changes: 135 additions & 0 deletions src/main/java/ProductsList.java
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import java.util.Scanner;
import java.util.ArrayList;

public class ProductsList {
static Scanner scanner = new Scanner(System.in);
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Можно убрать все модификаторы static, а при вызове методов в main создавать экземпляр класса ProductsList , и вызывать методы у него. Дальше по курсу будет рассказано, для чего static нужен

static String products; //Для названия товара
static double price; //Для цены
static ArrayList<String> listString = new ArrayList<>(); //Список для String
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Лучше назвать списки очевиднее, productList или products и priceList или prices

static ArrayList<Double> listDouble = new ArrayList<>(); //Список для Double
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Можно сделать ещё один класс, Product или Food, с полями name и price, и использовать его для записи каждого кушанья. Тогда вместо двух списков понадобится один список кушаний ArrayList<Food>

static int numbersOfGuests;


//**********************************************************************************************
//Метод для подсчёта гостей
public static int menuChoice() {
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Студия подсказывает, что возвращаемый тип метода не используется. Можно либо сделать метод void, либо использовать возвращаемый результат

while (true) { //Проверка
System.out.println("Введите количество гостей: ");

if (scanner.hasNextInt()) {
numbersOfGuests = scanner.nextInt();
if (numbersOfGuests > 1) {
System.out.println("сюда калькулятор");
productsChoice();
break;
} else if (numbersOfGuests == 1) {
System.out.println("И зачем я тогда писал калькулятор? " +
"Введите от 1-го, Христа ради: ");
} else if (numbersOfGuests == 0) {
System.out.println("Если у нас 0 гостей, тогда кого считаем то? " +
"Попытка No2: ");
} else {
System.out.println("Там умер кто?! " +
"Или почему кол-во гостей отрицательное? " +
"Давай ещё раз попробуем: ");
}

} else if (scanner.hasNextDouble()) {
System.out.println("Вы пришли с детьми! " +
"Как мило! " +
"Посчитайте их как взрослого человека: ");
scanner.nextLine();

} else {
System.out.println("Введите хотя-бы число: ");
scanner.nextLine();
}
}
return numbersOfGuests;
}

//**********************************************************************************************
//Метод для добавления названия и цены товарам
public static void productsChoice() {
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Метод можно сделать приватным, поскольку он используется только внутри этого класса


String answer;

while (true) {
System.out.println("Введите название товара: ");
products = scanner.next();
System.out.println("Введите цену товара: ");

while (true) {
if (scanner.hasNextDouble()) {
price = scanner.nextDouble();
if (price < 0) {
System.out.println("По-моему наш ресторан не так работает. " +
"Это не мы должны платить нам, а наоборот." +
"\nПрошу: ");
} else {
listString.add(products); //Добавляем в список название продукта
listDouble.add(price); //Добавляем в список цену продукта
System.out.println("Кушанье добавлено! ");
break;
}

} else {
System.out.println("Надо числами! Числами!!! " +
"Например 10.50 or 11.00, you know?: ");
scanner.nextLine();
}
}
//Спрашиваем хочет или не хочет, а может хочет и молчит? Хочет и молчит?
System.out.println("Не желаете ли вы добавить ещё товаров, мой господин?" +
"\nЕсли хотите, то шлёпните по клавиатуре ладонью и пусть будет что будет. " +
"\nКоли желаете завершить сей процесс, то так и напишите - \"Завершить\". " +
"\nНу либо же введите \"Да\", чтобы мне засчитали это в ТЗ: ");

answer = scanner.next();
if (answer.equalsIgnoreCase("Завершить")) { //Приводим всё к одному регистру и сверяем ввод с "Завершить"
//Показать продукты
System.out.println("Добавленные товары: ");
for (String s : listString) {
System.out.println("Кушанье: " + s); //Вывод всех товаров
}
break;

} else if (answer.equalsIgnoreCase("Да")) {
System.out.println("Молодец! Продолжаем: ");
} else {
System.out.println("Okay let's goooooooooo: ");
}
}
}

//**********************************************************************************************
//Соклько кто должен + окончания
public static Double debt() {
double sum = 0;
for (double d : listDouble) { //Считаем сумму
sum += d;
}
System.out.println("Всего накушали: " + endingRUB(sum));
System.out.println("Если по-чесноку, то с каждого: " + endingRUB(sum / numbersOfGuests));
return null;
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Лучше сделать метод void вместо возвращаемого типа Double, и эта строчка будет не нужна

}
//окончания
public static String endingRUB(double sum){
int ending = (int)sum % 10;
String formatEnding = String.format("%.2f", sum);
if (ending == 1){
return formatEnding + " рубль";
}
else if (ending >=2 && ending <= 4){
return formatEnding + " рубля";
}
else if (ending >= 5 && ending <= 20){
Copy link

@MagicUnderHood MagicUnderHood Nov 2, 2022

Choose a reason for hiding this comment

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

Поскольку ты проверяешь здесь результат деления по модулю 10 (%10), он не может быть больше 9, поэтому часть с ending <= 20 всегда будет true. Лучше здесь поставить default, а для проверки, что число у нас между 11 и 19, добавить перед этим if-else один с условием, что (int)sum % 100 >= 11 и <= 19

return formatEnding + " рублей";
}
else {
return formatEnding + " рублей";
}
}
}


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