1

因此,我使用 nextInt() 在命令行中从用户那里获取整数输入。但是,我的问题是;当用户不输入整数时,即只按回车而不输入任何内容,nextInt() 不会终止,而是继续提示用户,直到用户输入整数。是否可以将第一个“无输入”作为输入,然后返回一条错误消息,说明没有输入整数?提前致谢!

4

5 回答 5

1
 String line = null;
    int val = 0;
    try {
      BufferedReader is = new BufferedReader(
        new InputStreamReader(System.in));
      line = is.readLine();
      val = Integer.parseInt(line);
    } catch (NumberFormatException ex) {
      System.err.println("Not a valid number: " + line);
    } catch (IOException e) {
      System.err.println("Unexpected IO ERROR: " + e);
    }
    System.out.println("I read this number: " + val);
于 2012-08-26T08:48:11.917 回答
0

你可以尝试/捕捉。

String input = ....
try {
    int x = Integer.parseInt(input);
    System.out.println(x);
}
catch(NumberFormatException nFE) {
    System.out.println("Not an Integer");
}
于 2012-08-26T08:50:02.633 回答
0

尝试将输入作为字符串而不是整数。如果字符串为空,则应引发您提到的错误,否则将字符串转换为整数。我不知道你的程序流程是什么,所以它是一个一般的想法,根据输入需要解析字符串。此外,在使用此方法之前,您应该确保除了整数之外没有其他任何内容作为输入。

于 2012-08-26T08:51:34.707 回答
0

我假设您使用的是Scanner. 如果是这样,那么您需要指定您将使用哪个delimiter。像这样的东西:

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator")); 
while (scanner.hasNextInt()){
    int i = sc.nextInt();
    /** your code **/
}
于 2012-08-26T08:48:15.357 回答
0

尝试这个

 int number;
 boolean is_valid;

    do {
        try {
            System.out.print("Enter Number :");
            Scanner kbd = new Scanner(System.in);
            number = kbd.nextInt();
            is_valid = true;
        } catch (Exception e) {
            System.out.println("Invalid Integer ");
            is_valid = false;
        }
    } while (!is_valid);
于 2012-08-26T10:50:18.317 回答