如果需要用户输入整数,如何处理无效输入?

Man*_*Man 4 java exception input

我正在尝试编写一个程序,该程序接受用户整数输入并对其进行处理,并继续这样做直到用户输入非整数输入,此时将不再要求用户输入。这是我尝试过的:

import java.io.IOException;

public class Question2 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean active = true;
        String num_string_positive = "";
        String num_string_negative = "";
        int my_int;
        while (active) {
            try {
                my_int = in.nextInt();
            } catch(IOException e) {
                active = false;
            }
            in.close(); 
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用;catch 块似乎有问题。当我将鼠标悬停在 上时IOException,Eclipse 会显示“IOException 的无法访问的 catch 块。这个异常永远不会从 try 语句体中抛出”。当我调用该nextInt()方法时,非整数输入不应该抛出 I/O 异常吗?

当我用 替换catch(IOException e)catch(Exception e),代码确实运行,但它总是在一次输入后终止,即使输入是一个整数。

我究竟做错了什么?

Puj*_*rki 5

 public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while (sc.hasNextInt()) {
      System.out.println("Input is an integer.");
      sc.nextLine(); //Store this input in an array or variable as per your need.
    }
    int number = sc.nextInt();
  }
Run Code Online (Sandbox Code Playgroud)

此代码将检查输入是否为整数,如果是,则它将继续接受输入,一旦用户输入其他值,它将停止接受输入。