我不能离开我的while循环

SP *_*Wit 0 java while-loop

我为类活动编写了以下程序,提示用户输入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(); 
            }
        }
    }
}  
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

当用户输入"-1"时,它应该停止程序,然后打印出那些标记的平均值.

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

如果要允许-1,则应更改嵌套循环中的条件以允许它:

while (mark < -1 || mark > 100)
Run Code Online (Sandbox Code Playgroud)

另请注意,您在验证它之前使用mark是 - 所以如果输入10000,您仍然会total在请求新值之前添加10000,然后您将忽略新值.

此外,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");
    }
}
Run Code Online (Sandbox Code Playgroud)