Skip to content

Conversation

@sred75
Copy link
Owner

@sred75 sred75 commented Oct 31, 2022

Рабочий коммит - 050

import java.util.Scanner;
public class goodsEntering {
public static int goodsArrayCreating(){
int qtyOfGoods= 0;

Choose a reason for hiding this comment

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

Можешь применить в студии автоформатирование (в выбранном файле, сверху вкладка Code - Reformat Code, либо Ctrl+Alt+L), тогда автоматически код выправится.


System.out.println(calculator.cart);
System.out.println("Каждому человеку к оплате: " + formatter.roundResult(result) + " " + formatter.formatValue(result));
double payment = (double) sum / qtyOfGuys;

Choose a reason for hiding this comment

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

Приведение типа к double (код (double) перед sum) необязательно, потому что sum и так типа double

public static int goodsArrayCreating(){
int qtyOfGoods= 0;
String enteredName = "";
Double enteredPrice = 0d;

Choose a reason for hiding this comment

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

Double с большой буквы это класс-обертка, а здесь достаточно использовать примитив double. Подробнее про классы-обертки будет в спринте 3, тема 1, урок 2 Списки. ArrayList
Инициализация 0d здесь необязательно, поскольку до использования переменной её значение будет перезаписано enteredPrice = price.nextDouble();

Copy link
Owner Author

Choose a reason for hiding this comment

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

Очень долго промучился с проверками и типами данных(( В результате душевной травмы пробовал принудительно присваивать типы некоторым значениям переменных))
Стало большим сюрпризом, что нужно очищать буфер сканера, иначе случался вылет в ошибку...

Double enteredPrice = 0d;
Scanner name = new Scanner(System.in);
Scanner price = new Scanner(System.in);
while (!enteredName.equalsIgnoreCase("Завершить")) {

Choose a reason for hiding this comment

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

Можно сделать цикл бесконечным while(true), а при проверках ввода ставить break; для выхода из него

Copy link
Owner Author

Choose a reason for hiding this comment

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

Сэкономил строчки кода на проверках и break)) Спасибо, что обратили внимание 👍

qtyOfGoods = goodsEntering.goodsArrayCreating();

System.out.println("\nДОБАВЛЕННЫЕ ТОВАРЫ: ");
while (i < qtyOfGoods){

Choose a reason for hiding this comment

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

Можно вместо qtyOfGoods использовать goodsArray.size(). Это ещё и предотвратит от попытки получить элемент по индексу, который больше размера массива

@@ -0,0 +1,34 @@
import java.util.Scanner;
public class goodsEntering {
public static int goodsArrayCreating(){

Choose a reason for hiding this comment

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

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

import java.util.Scanner;
public class howManyGuys {
static int qtyOfGuys;
public static void main(String[] args) {

Choose a reason for hiding this comment

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

Этот метод здесь лучше убрать, потому что точка входа в приложение в методе main класса Main

public static int howManyGuys() {
boolean flag = false;
System.out.print("На какое кол-во человек разделить счёт? ");
while (!flag) {

Choose a reason for hiding this comment

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

Достаточно здесь написать в скобках true, и необходимости в переменной flag не будет

String payOutput;
int payInputNorm = (int) payInput;
String payString = Integer.toString(payInputNorm);
char endOfPayment = payString.charAt(payString.length() - 1);

Choose a reason for hiding this comment

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

Можно более простые варианты: для определения последней цифры - payInputNorm % 10. Плюс учесть, что для чисел 11-19 окончание слова - "рублей", поможет payInputNorm % 100

Copy link
Owner Author

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.

3 participants