'Java'System.out.println / do同时循环打印同一行两次

时间:2019-03-15 20:57:50

标签: java html loops do-while

我正在尝试创建一个程序,让您输入多个项目。所以我写了这段代码,问是否有多个项目。但是,当我运行代码时,它会显示“多于一个项目:输入//是/否//”两次。

我认为这样做的原因是因为yesNo没有值,所以代码将其读为yes或no,因此会循环。但是我不知道该如何解决。

do {
    System.out.println("More then one Item: Enter //Yes/No//");
    yesNo = input.nextLine();
} while ((!"yes".equalsIgnoreCase(yesNo) && !"no".equalsIgnoreCase(yesNo)));

如果可以帮助回答我的问题,这是我所有的代码。

import java.util.Scanner;

public class CreatePurchase {

    public static void main(String[] args) {

        Purchase purchase = new Purchase();

        Scanner input = new Scanner(System.in);

        int invoiceNum;
        double salesAmount;
        String itemName;
        String itemName2;
        String itemName3;
        String itemName4;
        String itemName5;
        String yesNo;

        do {
            System.out.println("Enter the Invoice Number.\nInvoice Number must be between 1000 & 8000:");
            invoiceNum = input.nextInt();

        } while (invoiceNum < 1000 || invoiceNum > 8000);

        do {
            System.out.println("Enter Sales Amount.\nPositive numbers only:");
            salesAmount = input.nextDouble();

        } while (salesAmount <= 0);

        do {
            System.out.println("More then one Item: Enter //Yes/No//");
            yesNo = input.nextLine();
        } while ((!"yes".equalsIgnoreCase(yesNo) && !"no".equalsIgnoreCase(yesNo)));

        if ("yes".equalsIgnoreCase(yesNo)) {
            System.out.println("Enter Item Name");
            itemName = input.nextLine();
            System.out.println("Enter second Item Name");
            itemName2 = input.nextLine();
            System.out.println("Enter third Item Name");
            itemName3 = input.nextLine();
            System.out.println("Enter fourth Item Name");
            itemName4 = input.nextLine();
            System.out.println("Enter fifth Item Name");
            itemName5 = input.nextLine();

            purchase.setInvoiceNum(invoiceNum);
            purchase.setItemName(itemName);
            purchase.setItemName2(itemName2);
            purchase.setItemName3(itemName3);
            purchase.setItemName4(itemName4);
            purchase.setItemName5(itemName5);
            purchase.setSalesAmount(salesAmount);

            purchase.displayPurchase();
        }

        if ("no".equalsIgnoreCase(yesNo)) {
            System.out.println("Enter Item Name");
            itemName = input.nextLine();

            purchase.setInvoiceNum(invoiceNum);
            purchase.setItemName(itemName);
            purchase.setSalesAmount(salesAmount);

            purchase.displayPurchase();
        }
    }
}

谢谢您的帮助! :)

0 个答案:

没有答案