简体   繁体   English

使用try-catch块的while循环在循环一次后不会等待try块中的输入

[英]While loop with try-catch blocks doesn't wait for input in the try block after looping once

So I've got a method getInput, that is meant to, well, ask user for input, use a try-catch to make sure it's a correct data type(int in this case) and validate whether it's in a predefined range. 因此,我有一个方法getInput,它的目的是,请用户输入信息,使用try-catch来确保它是正确的数据类型(在这种情况下为int)并验证它是否在预定义的范围内。 Problem is, when I enter, say, a string, it repeats the message about incorrect input, prints the message I have asking for input in try {} and goes straight to catch without waiting for input. 问题是,当我输入一个字符串时,它会重复输入错误的消息,并在try {}中打印我要求输入的消息,然后直接捕获而不等待输入。 Here's the code: 这是代码:

public static int getInput(String message, int lowerLimit, int upperLimit) {
    while (true) {
        int input;
        try {
            System.out.println(message);
            input = scanner.nextInt();
            if (lowerLimit > input && input > upperLimit) {
                return input;
            } else {
                System.out.println("Incorrect input value, try again");
            }
        } catch (Exception e) {
            System.out.println("Incorrect input, try again");
        }
    }
}

I know there are other, working ways of accomplishing this, but I'd like to know why this one doesn't work - I think it should. 我知道还有其他可行的方法可以实现这一目标,但是我想知道为什么这种方法行不通-我认为应该这样做。 Any ideas? 有任何想法吗?

if (lowerLimit > input && input > upperLimit)

This is ALWAYS false . 这总是false You meant 你的意思是

if (input >= lowerlimit && input <= upperLimit)
    return input;

The behaviour you're observing stems from the fact that scanner (assuming you're working with java.util.Scanner ) only advances if nextInt() is successful. 您观察到的行为源于以下事实:扫描程序(假设您正在使用java.util.Scanner )仅在nextInt()成功时才会前进。 That means that you have to skip over the faulty input (ie by using next() ) before proceding. 这意味着在继续操作之前,您必须跳过错误的输入(即,通过使用next() )。

Assuming you are using Scanner class, you could check, whether token has int or not 假设您使用的是Scanner类,则可以检查令牌是否具有int

 if(scanner.hasNextInt()){
  int input = scanner.nextInt();
     if (lowerLimit > input && input < upperLimit) {
     return input;
      } 
   }
  else 
   {
      System.out.println("Incorrect input value, try again");
    }

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

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