9

我需要检查用户输入值是否不是 int 值。我尝试了我所知道的不同组合,但我没有得到任何信息或随机错误

例如:

如果用户输入“adfadf 1324”,它会发出警告消息。


我有的:

       // Initialize a Scanner to read input from the command line
       Scanner sc = new Scanner(System.in);
       int integer, smallest = 0, input;
       boolean error = false;

       System.out.print("Enter an integer between 1-100: ");
       range = sc.nextInt();

       if(!sc.hasNextInt()) {

          error = true;
          System.out.println("Invalid input!");
          System.out.print("How many integers shall we compare? (Enter an integer between 1-100: ");
          sc.next();
    }

       while(error) {
          for(int ii = 1; ii <= integer; ii++) {

              ...

          } // end for loop
      }
      System.out.println("The smallest number entered was: " + smallest);

      }
  }
4

7 回答 7

19

如果输入无效,只需抛出异常

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}
于 2013-08-08T06:27:44.357 回答
6
Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }
于 2013-08-08T06:39:48.807 回答
2

试试这个代码[更新]

Scanner scan = null;
       int range, smallest = 0, input;

     for(;;){
         boolean error=false;
        scan = new Scanner(System.in);
        System.out.print("Enter an integer between 1-100:  ");


            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!");                      
                continue;
            }
         range = scan.nextInt();
            if(range < 1) {
                System.out.println("Invalid input!");
                error=true;
            }
        if(error)
        {
        //do nothing
        }
        else
        {
       break;
        }

        }
             for(int ii = 1; ii <= range; ii++) {
            scan = new Scanner(System.in);
            System.out.print("Enter value " + ii + ": ");

            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!"); 
               ii--;
                continue;
            } 
        }
于 2013-08-08T11:59:45.813 回答
2

您有以下错误,这反过来又导致您出现异常,让我解释一下

这是您现有的代码:

if(!scan.hasNextInt()) {
        System.out.println("Invalid input!");
        System.out.print("Enter an integer: ");
        usrInput= sc.nextInt();
    }

只有当用户输入既包含字符又包含像您的输入这样的整数时 ,上述代码中的代码if(!scan.hasNextInt())才会变为。trueadfd 123

但是您尝试使用 if 条件仅读取整数 usrInput= sc.nextInt();。哪个是不正确的,那就是投掷Exception in thread "main" java.util.InputMismatchException

所以正确的代码应该是

 if(!scan.hasNextInt()) {
            System.out.println("Invalid input!");
            System.out.print("Enter an integer: ");
            sc.next(); 
            continue;
        }

在上面的代码sc.next()中将有助于读取用户的新输入,并 continue有助于i.e if(!scan.hasNextInt())再次执行相同的 if condition()。

请在我的第一个答案中使用代码来构建您的完整逻辑。如果您需要任何解释,请告诉我。

于 2013-08-08T07:32:36.170 回答
0

也许你可以试试这个:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}
于 2015-03-26T07:23:26.353 回答
0

取自相关帖子

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}
于 2013-08-08T06:32:10.533 回答
0

这是为了在这个输入是整数时继续请求输入,并找出它是奇数还是偶数,否则它将结束。

int counter = 1;
    System.out.println("Enter a number:");
    Scanner OddInput = new Scanner(System.in);
        while(OddInput.hasNextInt()){
            int Num = OddInput.nextInt();
            if (Num %2==0){
                System.out.println("Number " + Num + " is Even");
                System.out.println("Enter a number:");
            }
            else {
                System.out.println("Number " + Num + " is Odd");
                System.out.println("Enter a number:");
                }
            }
        System.out.println("Program Ended");
    }
于 2015-11-11T09:01:38.937 回答