简体   繁体   English

WHILE循环条件无法验证输入

[英]WHILE Loop Condition Does Not Validate Input

I have a WHILE loop which checks for marks for a particular student. 我有一个WHILE循环,用于检查特定学生的成绩。 However, it does not loop if the value is invalid (input less than 0 and more than 100): 但是,如果值无效(输入小于0且大于100),则不会循环:

int marks= -1;

System.out.print("Student Marks (/100): ");
                while (((marks< 0) || (marks> 100))) {
                    try {
                        marks = Integer.parseInt(sc.nextLine());
                        break;
                    } catch (NumberFormatException nfe) { 
                        System.err.println("Error: Invalid Mark(s)");
                        System.out.print("Student Marks (/100): ");
                    }
                }

It does catches exception if characters other than numbers are entered. 如果输入数字以外的字符,则确实会捕获异常。

But it does not loop again if value if less than 0 or more than 100. 但是,如果值小于0或大于100,则不会再次循环。

I have tried making many changes to it but to no result. 我尝试对其进行许多更改,但没有任何结果。

Any help given is appreciated! 给予的任何帮助都将受到赞赏!

您应该删除break语句,因为无论输入什么marks值,它都会使您脱离循环。

You may check the marks inside the while loop with an if condition and here you may use break - 您可以使用if条件检查while循环内的marks ,这里可以使用break

import java.util.Scanner;

public class TakeInput{ 

    public static void main(String args[]){

        int marks= -1;
        Scanner sc = new Scanner(System.in);

        System.out.print("Student Marks (/100): ");
        while (sc.hasNext()) {
            try {
                marks = Integer.parseInt(sc.nextLine());
                if(marks<0 || marks>100){
                    break;
                }
                //do something
                // with the marks

                //take new marks
                System.out.print("Student Marks (/100): ");
            } catch (NumberFormatException nfe) { 
                System.err.println("Error: Invalid Mark(s)");
                System.out.print("Student Marks (/100): ");
            }
        }
    }

}  

Now as long as you enter anything except a number n when n<0 || n>100 现在,只要您在n<0 || n>100时输入除数字n以外的任何内容即可。 n<0 || n>100 will continue the loop. n<0 || n>100将继续循环。 Any NumberFormatExeption take you to the catch block. 任何NumberFormatExeption都会带您到catch块。

If you enter 34 then it goes to the while block and prompt for a next number. 如果输入34,则转到while块并提示输入下一个数字。 Then if you enter 56 then it dose the same thing. 然后,如果输入56,则表示相同。
When you enter any String rather than a number than it goes to the catch block 当您输入任何String而不是数字时,它将转到catch block
This process continues until you enter a invalid number (n>100 || n<100). 此过程将一直持续到您输入无效数字(n> 100 || n <100)为止。 Pressing Ctrl + C also exit you from the loop. Ctrl + C也会使您退出循环。

Hope it will help you. 希望对您有帮助。
Thanks a lot. 非常感谢。

如果要保持循环运行,请始终使用continue而不是break。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM