我无法摆脱我的 while 循环

I cant get out of my while loop

我为 class activity 编写的以下程序提示用户输入 0 - 100 之间的无限数量的测试标记,当用户输入超出该范围的标记时,它应该告诉用户认为它无效(到目前为止在我的程序中有效)。当用户输入“-1”时,它应该停止程序,然后打印出这些标记的平均值。

import java.util.*; 

public class HmWk62 {

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {


        int count=1; 
        int mark, total=0; 
        double average; 

        System.out.println("please enter mark "+count);
        mark = console.nextInt();
        count++; 

        while ((mark >= 0)&&(mark <= 100)){
            System.out.println("Please enter mark "+count);
            mark = console.nextInt(); 
            total += mark ;
            ++count; 

            while ((mark < 0)||(mark > 100)){
                System.out.println("Invalid mark, please re-enter");
                mark = console.nextInt(); 
            }
        }
    }
}  

When the user enters "-1" its should stop the program and then print out the average of those marks.

好吧,如果用户输入 -1,您将永远无法退出验证输入的 嵌套 循环。

如果你想允许-1,你应该改变嵌套循环中的条件来允许它:

while (mark < -1 || mark > 100)

另请注意,在验证之前,您使用 mark 的值 - 因此,如果您输入 10000,您仍会向 total 在你要求一个新值之前 - 然后你将忽略新值。

此外,您根本没有使用输入的 mark 的第一个值,除了查看您是否应该进入循环。

我怀疑你真的想要这样的东西:

while (true) {
    int mark = readMark(scanner, count);
    if (mark == -1) {
        break;
    }
    count++;
    total += mark;
}
// Now print out the average, etc

...

private static int readMark(Scanner scanner, int count) {
    System.out.println("Please enter mark " + count);
    while (true) {
        int mark = scanner.nextInt();
        if (mark >= -1 && mark <= 100) {
            return mark;
        }
        System.out.println("Invalid mark, please re-enter");
    }
}

让您的代码检查是否设置了全局变量。

例如,创建变量:boolean userCancelled = false;

在 while 循环中检查这个变量: 喜欢:

while (userCancelled  != false && (mark >= 0)&&(mark <= 100))
{
 }

内部 while 循环就是您陷入其中的那个。

一方面,你需要一个无效的标记才能退出, 但另一方面,该程序会拒绝无效标记并不断询问,直到您输入有效标记。

结果 - 你卡住了。

解决方法: 把里面的while改成一个if,在if块里放一个System.exit()的平均计算代码。

我建议您用下面的 do while loop 替换 while 循环:

    do {
        System.out.println("Please enter mark "+count);
        mark = console.nextInt(); 
        if(mark == -1){
           break;
        }else if((mark >= 0)&&(mark <= 100)){
           total += mark ;
           ++count; 
        }else{
            System.out.println("Invalid mark, please re-enter");
            mark = 0; 
        }
    } while ((mark >= 0)&&(mark <= 100));