检查输入值是否为整数类型java

时间:2013-11-05 18:10:53

标签: java validation input

我正在请求用户输入他需要写整数的位置。我设法创建验证,检查值是否高于所需值,因此,使用以下代码:

int n = sca.nextInt(); 
while (n<=0){
    System.err.println(error_1);
    n = sca.nextInt(); 
}                    

但现在如何添加字符串检查,我找到了这样的解决方案How do I keep a Scanner from throwing exceptions when the wrong type is entered?

在实际阅读输入之前使用hasNextInt(),我尝试将此检查放在同一个地方,而n<=0就像这样

while ( (n<=0)||(sca.hasNextInt() )) {
  ....
}

但它回答错误,变量n与该方法不兼容。 那么有什么方法可以克服这种情况吗?

4 个答案:

答案 0 :(得分:5)

您可以使用parseInt并检查异常:

public boolean parseWithFallback(String text) {
try {
  Integer.parseInt(text);
  return true;
} catch (NumberFormatException e) {
 return false;
 } 
}

答案 1 :(得分:2)

如果您不检查输入是否为nextInt()类型,则首次调用int也会导致异常。

希望以下将解决您的问题。

Scanner sca = new Scanner(System.in);

boolean incorrectInput = true;
int userInput = -1; // initialize as a negative  

while (incorrectInput) {

    if (sca.hasNextInt()) {
        int n = sca.nextInt();
        if (n < 0) {
            System.err.println("error_1");
        } else {
            // do anything else
            userInput = n;
            incorrectInput = false;
        }
    } else {
        sca.next();
    }
}

if (!incorrectInput) {
    System.out.println("UserInput = " + userInput);
}

答案 2 :(得分:1)

在尝试获取下一个Int之前,您必须测试是否存在下一个Int。

boolean finished = false;
while(!finished){
  while(scan.hasNextInt()){
    int n = sca.nextInt(); 
    if(n <= 0){
      System.out.println("Error: Number smaller 0");
    } else {
      System.out.println("correct!");
      finished = true;
    }
  }
}

答案 3 :(得分:0)

您可以根据需要多次请求和验证用户输入。

heq1(sol$par)
## [1] -4.969690e-09  5.906888e-09  1.808652e-08

您必须创建两个继承Exception类的类NotIntUserInputException和NotPositiveIntUserInputException

相关问题