почему my! = 0 не работает в то время как l oop? - PullRequest
0 голосов
/ 27 февраля 2020

Напишите программу, которая имитирует кассу терминала. Предположим, что покупатель покупает неизвестное количество различных товаров, возможно, с несколькими количествами каждого товара. Используйте некоторое время l oop, чтобы запросить цену за единицу и количество. Значение l oop должно продолжаться до тех пор, пока цена за единицу не станет равной нулю. Показать промежуточный итог для каждого элемента. После l oop отображается общая сумма к оплате. При необходимости используйте формат валюты.

import java.util.Scanner;

public class Program4 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter item price or zero to quit: ");
        double price = input.nextDouble();

        System.out.println("Enter the quantity for this item: ");
        int qty = input.nextInt();

        double Sub_Total = price * qty;

        System.out.printf("Total of this item is $%4.2f", Sub_Total);
        System.out.println();


        double Total = 0;

        while(price != 0) {
            System.out.println("\nEnter item price or zero to quit: ");
            price = input.nextDouble();

            System.out.println("Enter the quantity for this item");
            qty = input.nextInt();

            Sub_Total = price * qty;

            System.out.printf("Total of this item is $%4.2f", Sub_Total);
            System.out.println();


            Total += Sub_Total; 
        }
        System.out.printf("Total is $%5.2f" + Total);

    }

}

Я делаю программу для школы и не могу понять, почему мое время l oop не заканчивается, когда я набираю 0.

Ответы [ 4 ]

1 голос
/ 27 февраля 2020

l oop заканчивается при вводе 0; проблема в том, что ваше println утверждение находится за пределами l oop. Ваш код должен выглядеть следующим образом:

      ...
      Total += Sub_Total;
      System.out.printf("Total is $%5.2f", Total);
      }
   }
}

Если вы хотите, чтобы ваша программа заканчивалась сразу после ввода 0, вы можете добавить оператор if:

Scanner input = new Scanner(System.in);

System.out.println("Enter item price or zero to quit: ");
double price = input.nextDouble();

if (price <= 0) {
    System.out.println("input: zero - program terminated.");
    return; 
}
...

. для эффективной работы код должен быть реструктурирован. Он также может быть оптимизирован для устранения избыточности; следующие условия должны обработать условия и правильно завершиться:

import java.util.*;

class Untitled {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    double total = 0;
    double subtotal = 0;
    double qty = 0;

    System.out.println("Enter item price or zero to quit: ");
    double price = input.nextDouble();

    while (price > 0) {

        System.out.println("Enter the quantity for this item: ");
        qty = input.nextDouble();

        subtotal = price * qty;
        total += subtotal;

        System.out.printf("Total of this item is $%4.2f", subtotal);
        System.out.println();

        System.out.println("\nEnter item price or zero to quit: ");
        price = input.nextDouble();

        if (price <= 0)
            break; 
        }
        System.out.printf("Total is $%5.2f", total);
    }
}

Как уже упоминалось в комментариях следуйте соглашениям, используя строчные буквы для имен переменных.

0 голосов
/ 27 февраля 2020

Это должно быть решением для вас, здесь я дал комментарий, где ваш код имеет проблемы

public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter item price or zero to quit: ");
        double price = input.nextDouble();

        System.out.println("Enter the quantity for this item: ");
        int qty = input.nextInt();

        double Sub_Total = price * qty;

        System.out.printf("Total of this item is $%4.2f", Sub_Total);
        System.out.println();


        double Total = Sub_Total;  //changed this line to get correct total

        while(price != 0) {
            System.out.println("\nEnter item price or zero to quit: ");
            price = input.nextDouble();

            if(price == 0.0) 
                break;

            System.out.println("Enter the quantity for this item");
            qty = input.nextInt();

            Sub_Total = price * qty;

            System.out.printf("Total of this item is $%4.2f", Sub_Total);
            System.out.println();


            Total += Sub_Total; 

        }
        System.out.printf("Total is $%5.2f", Total); //this also needs to be changed to print output in correct format, 
                                                     //otherwise you will get missing element exception

    }
0 голосов
/ 27 февраля 2020

После ввода цены вы можете проверить ее, используя условие if, если цена равна 0, вы можете использовать break, чтобы остановить l oop

public class Program4 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter item price or zero to quit: ");
        double price = input.nextDouble();

        System.out.println("Enter the quantity for this item: ");
        int qty = input.nextInt();

        double Sub_Total = price * qty;

        System.out.printf("Total of this item is $%4.2f", Sub_Total);
        System.out.println();


        double Total = 0;

        while(price != 0) {
            System.out.println("\nEnter item price or zero to quit: ");
            price = input.nextDouble();

            if(price == 0)
            break;

            System.out.println("Enter the quantity for this item");
            qty = input.nextInt();

            Sub_Total = price * qty;

            System.out.printf("Total of this item is $%4.2f", Sub_Total);
            System.out.println();


            Total += Sub_Total; 
        }
        System.out.printf("Total is $%5.2f",Total);

    }

}
0 голосов
/ 27 февраля 2020

вычисления с использованием типов с плавающей точкой (double и float) могут быть неточными, поэтому обычно лучше проверить, близко ли это к 0. Пожалуйста, проверьте ниже фрагмент

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter double val::");
    double d = scanner.nextDouble();

    while (Math.abs(d) <  Double.MIN_VALUE) {
        System.out.println("DoubleTest::d::::" + d);
    }
...