Java-программа выдает неправильный вывод. (В то время как контур) - PullRequest
0 голосов
/ 05 октября 2019

Вот пример того, как должен выглядеть вывод !!

Моя программа для отображения сводки заказов для приобретенных ноутбуков использует цикл (1) while для обработки нескольких ноутбуков,(2) если-либо, чтобы получить имя / цену ноутбука;или сообщение об ошибке «Неверный выбор! Попробуйте еще раз», a (3) вложено, если выяснить, когда выбор портативного компьютера действителен для продолжения обработки. И (4) вложено, если печатать сводку заказов только при покупке ноутбуков.

Когда я вводю неправильный номер (например, 8) в выбор, оператор if все равно выполняется, а не другой, который находится ниже него.
Когда я вписываю действительное число в выбор, он запрашивает количество, но когда я вводю количество, как бы я добавил этот пользовательский ввод в сводку заказа вместо программы, возвращающейся в верхнюю часть цикла?

Я очень плохо знаком с Java, как должен выглядеть мой код для получения правильного вывода?

Вот мой текущий код (JAVA)

public static void main(String[] args) { 
    char cont='Y';
    int qty=0;
    int trigger=0;

    double total=0;
    double subtotal=0;
    double tax=0;
    double price;
    double lineItem=0;

    String orderSummary=" ";
    String laptop=" ";
    Scanner input = new Scanner(System.in);
    Calendar dateTime = Calendar.getInstance();

    //Displays a list of laptops with prices and asked user for their choice. Prompt #1
    int choice = 0;

    while (choice >= 0) {  
        System.out.printf("%nTOP LAPTOPS OF %tY"
                        + "%n%n1. %-23s %7s $%,9.2f"
                        + "%n2. %-23s %8s %,9.2f"
                        + "%n3. %-23s %8s %,9.2f"
                        + "%n4. %-23s %8s %,9.2f"
                        + "%n5. %-23s %8s %,9.2f"
                        + "%n%nEnter your choice: ",
                      dateTime,
                      "HP Envy 13", " ", 799.99, 
                      "Asus ZenBook 13 UX333FA", " ", 849.99,
                      "Dell XPS 13", " ", 989.99,
                      "Alienware Area 51-m", " ", 1999.99,
                      "Razer Blade Stealth", " ", 1299.00);

        choice = input.nextInt();

        if (choice < 6 || choice > 0) {
          System.out.printf("Enter the quantity:");
          qty = input.nextInt();
        } else {
          System.out.printf("Invalid choice! Try again.%n%n");
          System.out.printf("Enter 'Y' to add a laptop to your purchase or 'N' to exit: ");
          cont = input.next().charAt(0);
        }
        if (cont == 'Y') {
          continue;
        }
        if (cont == 'N') {
          System.exit(0);
        }

        //The following if-else prints a $ sign for the first line item
        if (trigger == 1) {
          orderSummary += String.format("%n%, -9d %-30s %8s $%,17.2f", qty, laptop, " ", lineItem);
          trigger = 0;
        } //End else for no $ sign

        //The following statement prints the order summary of the laptops purchased.
        //This should be done when there are no more laptops to process
        if (choice > 0) {
            if (choice < 6) {
                tax = subtotal * .0825;
                total = subtotal + tax;

                orderSummary += String.format("%n%n%34s Subtotal %6s %,17.2f"
                                            + "%n%31s Tax @ 8.25%% %6s %,17.2f"
                                            + "%n%n%37s TOTAL %5s $%,17.2f%n",
                                          " ", " ", subtotal,
                                          " ", " ", tax,
                                          " ", " ", total);
                System.out.printf("%s", orderSummary);
                break;
            } //End if valid choice range ends print order summary  
        } //End if valid choice range begins
    }
} 

1 Ответ

0 голосов
/ 05 октября 2019

Поскольку правила операторов AND (&&) OR (&&) соответствуют булевой алгебре.

if (choice <6 || choice> 0) соответствует 'if choice <8' - True ИЛИ if 'выбор> 0 'истинен, тогда все выражение истинно

например, для 8 выбранных это будет ИСТИНА, иначе не произойдет

попробуйте, если (выбор> 0 && выбор <6) </p>

Затем подумайте о «бизнес-логике», подготовьтесь к сохранению и повторному использованию, систематизируйте свою переменную для расчета, см. Пример ниже

import java.util.*;

public class Example{
public static void main(String[] args) {


String [] product = {"HP Envy 13","Asus ZenBook 13 UX333FA","Dell XPS 13","Alienware Area 51-m","Razer Blade Stealth"};
double [] unit_rate = {799.99, 849.99, 989.99, 1999.99, 1299.00};
int [] user_selectected_qty = new int [product.length]; 

double total = 0;
boolean again = true;

Scanner input = new Scanner(System.in);
int choice,qty;

while (again)
{

    System.out.println("TOP LAPTOPS");
    for(int i=1; i<product.length ; i++)
        System.out.println(""+i+".\t"+product[i]+"\t\t\t"+unit_rate[i]);

    System.out.println("Enter your choice:");
    choice = input.nextInt();

    // SELECTION PROCESS
    if (choice >0 && choice <6)
    {
    System.out.println("Enter the quantity for "+product[choice]+":");
    qty = input.nextInt();
    user_selectected_qty[choice]+=qty;  


    // ... ASK TO DO IT AGAIN...


    again=false;

    }
    else
    {
     System.out.println("Wrong choice:");
    }

}
    // BEFORE END SHOW SUMMARY  ...COMPUTE TOTAL ...
    System.out.println("LAPTOP ORDER SUMARY");

    for(int i=1; i<product.length ; i++)
        if (user_selectected_qty[i] > 0)
            System.out.println(""+user_selectected_qty[i]+"\t"+product[i]+"\t\t\t"+unit_rate[i]*user_selectected_qty[i]);





}
}
...