如何检查用户输入是否不是int值

时间:2013-08-08 06:23:42

标签: java validation

我需要检查用户输入值是否不是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);

      }
  }

7 个答案:

答案 0 :(得分:17)

如果输入无效,则简单地抛出异常

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");
}

答案 1 :(得分: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;
  }

答案 2 :(得分:2)

你有以下错误,这反过来导致你的异常,让我解释一下

这是您现有的代码:

if(!scan.hasNextInt()) {
        System.out.println("Invalid input!");
        System.out.print("Enter an integer: ");
        usrInput= sc.nextInt();
    }
只有当用户输入同时包含字符以及输入if(!scan.hasNextInt())之类的整数时,上述代码true中的

才会变为adfd 123

但您尝试使用usrInput= sc.nextInt();只读取if条件内的整数。这是不正确的,那就是投掷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将有助于再次执行相同的if条件(i.e if(!scan.hasNextInt()))。

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

答案 3 :(得分: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;
            } 
        }

答案 4 :(得分:0)

取自related post

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;
}

答案 5 :(得分: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;
}

答案 6 :(得分: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");
    }