Java数据验证

Java数据验证,java,Java,我正在尝试创建一个数据验证程序,以确认我有一个整数,以及一个介于0和4之间的整数。我当前的代码卡在嵌套的If-Else语句的循环中,我不知道为什么。感谢您的帮助 Scanner in = new Scanner ( System.in); int lives; lives = 0; boolean isNumber; do { System.out.println ( "How many lives do you currently have? (Ma

我正在尝试创建一个数据验证程序,以确认我有一个整数,以及一个介于0和4之间的整数。我当前的代码卡在嵌套的If-Else语句的循环中,我不知道为什么。感谢您的帮助

   Scanner in = new Scanner ( System.in);
   int lives;
   lives = 0;
   boolean isNumber;
   do {
       System.out.println ( "How many lives do you currently have? (Max. 4): " );
       if ( in.hasNextInt() ) {
           lives = in.nextInt();
            if (lives > 4){
                System.out.println ( "Please try again. Number must be between 1 and 4" );
                isNumber = false;
                in.next ();
           }
           else {
           lives = in.nextInt();
           isNumber = true; 
           }
       }
       else {
           System.out.println ( "Please try again. Number must be between 1 and 4" );
           isNumber = false;
           in.next ();
       }
   }
   while (! (isNumber ) );
尝试查看,看看in.hasNextLine()中的内容是否与in.hasNextLine()中的内容相同

Scanner in = new Scanner(System.in);
    int lives = 0;
    boolean isNumber = false;
    do {
        System.out.println("How many lives do you currently have? (Max. 4): ");
        if (in.hasNextLine()) { // when enter key has been hit
            try {
                lives = Integer.parseInt(in.nextLine().trim());
                if (lives < 1  || lives > 4) {
                    System.out.println("Please try again. Number must be between 1 and 4");
                    isNumber = false;
                } else {
                    isNumber = true;
                }
            } catch (NumberFormatException e) {
                //Report your error here to the user
                System.out.println("Please enter a number");
                isNumber = false;
            }
        } 

    } while (!(isNumber));
Scanner-in=新的扫描仪(System.in);
int=0;
布尔值isNumber=false;
做{
System.out.println(“你目前有多少条生命?(最多4条):”;
如果(在.hasNextLine()中){//当按下回车键时
试一试{
lives=Integer.parseInt(in.nextLine().trim());
如果(寿命<1 | |寿命>4){
System.out.println(“请重试。数字必须介于1和4之间”);
isNumber=false;
}否则{
isNumber=true;
}
}捕获(数字格式){
//在此处向用户报告您的错误
System.out.println(“请输入一个数字”);
isNumber=false;
}
} 
}而(!(isNumber));

您是否尝试过调试代码?它卡在哪里?是否所有的测试用例都会导致无限循环?例如,当您输入2时,会发生什么?代码将循环返回并解释数字不正确。如果我输入一个字符串,它将返回并再次询问。如果我输入一个不在0和4之间的数字,代码将返回并再次询问。如果我输入了一个有效的数字,代码将停止,并且不会启动我正在研究的问题。我感谢@rohlex32的链接,感谢你今天超越一切帮助我。昨天晚上我的头撞在墙上,今天早上我想找到一个有效的验证器。我并不真正理解catch异常方法,但在这一点上,我将使用它,并进一步研究它,了解它。欢迎使用。有时,用户可能会在控制台输入中输入非数字字符,{try-catch}会帮助您防止这种情况