Java程序循环将不会执行,并提示用户? [关闭](Java Program Loop won&

2019-10-21 08:11发布

好了,所以我只能通过我的数组库存计划的方式组成部分,但应该提示用户重新输入号码时,他们已经进入了一个无效将不执行我的while循环。 当输入程序为无效号码刚刚结束......我曾尝试一些方法,也不是工作。 这就是我在现在,任何想法?

非常感谢!

public class InventorySystem {

    public static void main(String[] args) {
        String[] newItemInfo = new String[1000];
        String[] itemDescription = new String[1000];
        int[] itemPrice = new int[1000];
        int choice;
        boolean isValid;
        int itemChoice;

        Scanner inputDevice = new Scanner(System.in);
        System.out.println("*****Raider Inventory System*****");
        System.out.println("1. Enter a new item");
        System.out.println("2. View Item Information");
        System.out.println("3. View a list of all items");
        System.out.println("9. End Program\n");
        System.out.println("Please enter your selection: ");
        choice = inputDevice.nextInt();

        if (choice == 1 || choice == 2 || choice == 3 || choice == 9) {
            isValid = true;
        } else {
            isValid = false;
        }

**      while (isValid = false) {
            System.out.println("Invalid entry, please enter either 1, 2, 3, or 9 for menu options.");
**      }

        for (int x = 0; x < 1000; ++x) {
            if (choice == 1) {
                System.out.println("Please enter the name if the item: ");
                newItemInfo[x] = inputDevice.nextLine();
                System.out.println("Please enter the item description: ");
                itemDescription[x] = inputDevice.nextLine();
                System.out.println("Please enter item price: ");
                itemPrice[x] = inputDevice.nextInt();
            }
        }

        if (choice == 2) {
            System.out.println("***Show item Description***");
            System.out.println("0. ");
            System.out.println("please enter the item number ot view details: ");
            itemChoice = inputDevice.nextInt();
        }

        if (choice == 3) {
            System.out.println("****Item List Report****");
        }

        if (choice == 9) {
            System.exit(0);
        }
    }
}

Answer 1:

不要做while (isValid = false) 你将它设置为假的!

相反,做

while (!isValid) {

}

另外,不要做while (isValid == false) -这是丑陋的代码。

其次,改变循环内的IsValid。

while (!isValid) {

   // get input from user in here

   // test input and check if is valid. If so, set isValid = true;

   // something must set isValid to true in here, else it will 
   // loop forever      
}

否则,你会停留在一个无限循环。 这个教训在这里学到的是在精神上通过您的代码行,如果你是在你的大脑运行它。 这样,你赶上喜欢你有什么逻辑错误。



Answer 2:

在你行

while(isValid = false)

=没有做什么,你认为它。 在Java中,一个单一=意味着在右侧的表达式分配给左侧的变量 。 这并不意味着双方进行比较。

所以,你应该宁可这样写:

while (isValid == false)

需要注意的双重== 。 此代码的工作,但你可以更加精美写:

while (!isValid)

! 意味着没有



文章来源: Java Program Loop won't Execute and Prompt User? [closed]