Java While在switch语句中循环以验证用户输入,但继续获取无效输入,尽管它是有效的。

Java While在switch语句中循环以验证用户输入,但继续获取无效输入,尽管它是有效的。,java,validation,while-loop,Java,Validation,While Loop,因此,我创建了一个菜单,用户可以从一系列选项中进行选择,但我在让用户输入有效选项时遇到了麻烦。我曾尝试在案例1中使用while循环,但每次我键入1或2这两个有效输入时,我的输出都是“无效输入”。这是我菜单的一部分: int choice; double amount; Scanner input = new Scanner(System.in); while(true) { System.out.printf("\n********* MENU *****

因此,我创建了一个菜单,用户可以从一系列选项中进行选择,但我在让用户输入有效选项时遇到了麻烦。我曾尝试在案例1中使用while循环,但每次我键入1或2这两个有效输入时,我的输出都是“无效输入”。这是我菜单的一部分:

int choice;
    double amount;
    Scanner input = new Scanner(System.in);
    while(true) {
        System.out.printf("\n********* MENU ************\n1. Check balance\n2. withdraw\n3. Deposit\n4. Change Annual Interest Rate\n5. Calculate Monthly Interest\n6. Display Account Info\n7. Exit\nEnter your choice: ");
        choice = input.nextInt();
        switch(choice) {
            case 1: System.out.printf("Check balance for saver1(1) or saver2(2)? ");
                    choice = input.nextInt();
                   while(choice != 1 || choice != 2) {
                    System.out.printf("Please enter a valid choice: ");
                     choice = input.nextInt();
                   }
                    if(choice != 1 || choice != 2) {
                        System.out.printf("Invalid input: ");
                        choice = input.nextInt();
                    }
                    if(choice == 1) {
                        System.out.println(saver1.getBalance());
                    } else {
                        System.out.println(saver2.getBalance());
                    }
                    break;

更改条件
choice!=1 | |选择!=2
在while循环和if语句中

choice != 1 && choice != 2

因为问题是,如果您输入
1
,那么这将不等于
2
。因此,原始条件的计算结果将为true,因为尽管表达式的左侧
choice!=1 | |选择!=2
将计算为false,右侧将计算为true,使整个表达式计算为true。在这种情况下,您将永远无法离开循环,因为您无法实际输入
1
2
的数字,如果您键入1,则选项将等于1,但也不等于2,这意味着即使您键入1 If语句:

if(choice != 1 || choice != 2) {
                    System.out.printf("Invalid input: ");
                    choice = input.nextInt();
                }
仍将执行,因为选项不等于2