Skip to content

Выполненная проектная работа №1 - #1

Open
hasket wants to merge 7 commits into
mainfrom
dev
Open

hasket wants to merge 7 commits into
mainfrom
dev

Conversation

@hasket

@hasket hasket commented Oct 22, 2023

Copy link
Copy Markdown
Owner

No description provided.

Artem Vazerov added 2 commits October 21, 2023 13:04
…ограмма не очень аохожа на программу программиста, но я обдумывал это решение до пол 2-го ночи, вроде даже реально похоже на подобие норм программы.

try {
// вызывал конструктор parseDouble типа Double и перевожу строку в double
// Сам я не додумался, а за меня додумался интернет

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Это норма) Главное уметь искать и понимать, что ты нашел)

Comment thread src/main/java/Calculator.java Outdated

public static double sumPrice(HashMap <String, Double> productsMap){
double sumPriceResult = 0.00f;
for (Object i: productsMap.keySet()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Так как у мапы тип ключей String, то вместо Object было бы корректнее сразу написать String

Comment thread src/main/java/Formatter.java Outdated
Comment on lines +4 to +7
if (floor(price) == 1.00 || floor(price) == 1.0) {
return "рубль";
}
return "рубля";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Есть несколько случаев:

  1. Оканчивается на 1- рубль
  2. 3-4 - рубля
  3. 0, 5-9, 11 - 19 - рублей

Comment thread src/main/java/Main.java Outdated
I'm so sorry

##
## Calculator vashego nastorenia version 0.3

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Люблю такие комментарии (❁´◡`❁)

Comment thread src/main/java/Main.java Outdated

while (humans <= 1) {
System.out.print("Введите количество гостей ");
humans = scanner.nextInt();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если ввести не интовое значение, то упадет. Нужно либо оборачивать в try-catch, либо проверять ввод через метод scanner.hasNextInt()

Formatter formatter = new Formatter();
double productsSum = 0.00f;
double productPrice = 0.00f;
HashMap<String, Double> productsMap = new HashMap<String, Double>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Отличный вариант использовать мапу)

Comment thread src/main/java/Product.java Outdated
// Сам я не додумался, а за меня додумался интернет
productPrice = Double.parseDouble(scanner.next());
if (productPrice > 0) {
productsMap.put(productName, productPrice);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь съехало форматирование, должен быть сдвинут на таб блок. Поможет комбинация ctrl + alt + L или cmd + opt + L

Comment thread src/main/java/Product.java Outdated
System.out.println("Добавленные товары:\n");
for (String i : productsMap.keySet()) {
System.out.printf("Товар \"%s\" стоимостью \"%s\" %s\n", i,
productsMap.get(i).toString().replace(",", "."),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread src/main/java/Product.java Outdated
productsMap.put(productName, productPrice);
System.out.println("Товар успешно добавлен\n");

System.out.print("Желаете добавть ещё товар? \n");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Опечаточка в добавить

Comment thread src/main/java/Product.java Outdated
wishQuestion.equalsIgnoreCase("нет")) {
System.out.println("Добавленные товары:\n");
for (String i : productsMap.keySet()) {
System.out.printf("Товар \"%s\" стоимостью \"%s\" %s\n", i,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Чтобы слегка облегчить метод и улучшить читаемость, все эти принты можно было бы вынести в отдельный метод

}
return "рубля";
// Это студия такой красивый формат(котлин стайл)
// привела, сам не догадался =(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Все приходит с опытом) Потом привыкнешь и уже будет у самого глаза болеть от кривого форматирования))

Comment thread src/main/java/Formatter.java Outdated
return "рубля";
// Это студия такой красивый формат(котлин стайл)
// привела, сам не догадался =(
return switch ((int) floor(price)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Чтобы проверить правильно окончание, следует посчитать два значения: 1) Последнюю цифру числа - это остаток от деления на 10, то есть price % 10. 2) Последние две цифры - это остаток деления на 100: price % 100.

Далее первым делом надо проверить, входит ли остаток от деления на 100 в диапазон 11-19. Это тот случай, когда будет рублей.
Потом проверяем остаток деления на 10. Если 1 - это рубль (чтобы учесть случаи, когда число кончается на 1: 21, 31, 101 и тд). Если 2-4 - рубля. И остальное будет рублей

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

про деление по модулю знаю, использовал, тут не стал по невнимательности.
и не учёл про то, что цена может быть больше 19-ти рублей

Comment thread src/main/java/Main.java
if (humans < 1) {
System.out.println("Счёт не делится на такое количество человек.\n" +
"Введите корректное число людей");
try {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

image

formatter.Formatter(productsSum));
System.out.printf("Каждый посетитель должен заплатить %.2f %s \n",
Calculator.priceForPerson(productsMap, humans),
//Насколько правильно вызвать функцию, в которой вызывается функция? <------

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Да в целом так делают) Если выражение не становится супер сложным и длинным

Artem Vazerov added 4 commits October 24, 2023 00:35
…у синтаксиса при ошибках, поправил ввод числа, теперь он и с запятой правильно записывает и с точкой
int modPrice = (int) (floor(price));
//это хотфикс, потом понял, где неправильно
// и в итоге не смог быстро всё пофиксить по нормальному
if (modPrice % 100 > 11 && modPrice % 100 < 15)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ну вообще можно было просто сохранить mod 10, mod 100, а потом в свитч кейсе сначала мод 100 проверить на 11-15, а потом мод 10 на все остальное

Comment thread src/main/java/Main.java
}
} catch (Exception e) {
System.err.println("Ёкарный бабай, шнурок, целое число больше одного введи");
// Как понял из описаний в интернетах, из-за того, что первый раз мы вводим неправильный

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Я тоже так поняла))

} else {
System.out.println("Ёкарный бабай, шнурок, когда последний раз за " +
"твой кофе заправка платила?");
//Моя девушка сказала, раз эт неправильно, то почему оно не красится=)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ничесе, я такого варианта еще не встречала в этой работе)) Девушке респект

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants