在程序运行时,Do-While循环连续打印

时间:2017-01-15 04:05:53

标签: java loops do-while

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

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);

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

2 个答案:

答案 0 :(得分:3)

替换

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);

答案 1 :(得分:1)

您可能想要更正

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

因为,它始终是 true

如果您始终要执行do..while语句块,则可以删除此(do{...})条件。 (“......我只想发生一次”)