我的程序中使用了以下代码:

do {
    if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) {
        addItems(numOfItems);

    } else {
        System.out.println("That number is out of range.");
        System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
        numOfItems = scan.nextInt();
    }
} while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);


在运行时,它会不断重复我只想发生一次的方法。如何使循环不断重复进行验证,但只运行一次该方法?

最佳答案

更换

while (numOfItems != 3 || numOfItems != 5 || numOfItems != 7 || numOfItems != 9);



while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);

更新资料

从您的评论到答案,您似乎需要执行以下操作:

do {
    numOfItems = scan.nextInt();
    if (numOfItems == 3 || numOfItems == 5 || numOfItems == 7 || numOfItems == 9) {
        addItems(numOfItems);

    } else {
        System.out.println("That number is out of range.");
        System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");

    }
} while (numOfItems != 3 && numOfItems != 5 && numOfItems != 7 && numOfItems != 9);


但是,您可以对此进行优化,如下所示:

while ((numOfItems = scan.nextInt() != 3) && numOfItems != 5 && numOfItems != 7 && numOfItems != 9) {

            System.out.println("That number is out of range.");
            System.out.println("Please choose an odd number in the range of [1, 10] exclusively:");
}

addItems(numOfItems);

10-08 14:58