如何阻止用户在此read()方法中输入String?

Dan*_*iel 1 java

每次输入String或Char时,我的read()方法都会崩溃.我怎么能让它只接受整数值.当我输入一个int,它工作正常,但当我输入一个字符串或字符串时,我得到一个重复的"输入帐户打开的那天:null"错误.我必须终止程序才能阻止它.

private void readDay(Scanner keyboardIn) {
    boolean success = false;
    while (!success) {
        try {
            System.out.print("Enter the day the account opened: ");
            int d = keyboardIn.nextInt();
            dateOpened.setDay(d);
            success = true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

// Enter the month, checking for error
private void readMonth(Scanner keyboardIn) {
    boolean success = false;
    while (!success) {
        {
            try {
                System.out.print("Enter the month the account opened: ");
                int m = keyboardIn.nextInt();
                dateOpened.setMonth(m);
                success = true;
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}


// Enter the year, checking for error
private void readYear(Scanner keyboardIn) {
    boolean success = false;
    while (!success) {
        try {
            System.out.print("Enter the year the account opened: ");
            int y = keyboardIn.nextInt();
            dateOpened.setYear(y);
            success = true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 5

您无法阻止用户输入非数字; 你只需要处理它.

而不是尝试读取数字,在循环中读取一个字符串:

  • 如果输入数字,则将其解析为整数,使用数字,然后停止循环.
  • 如果他们输入其他内容,则打印消息并保持循环.

像这样的东西:

while (true) {
  String line = keyboardIn.nextLine();
  if (line.matches("\\d+")) {
    int d = Integer.parseInt(line);
    dateOpened.setDay(d);
    break;
  }

  System.out.println("Must be an integer; try again.");
}
Run Code Online (Sandbox Code Playgroud)