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

时间:2016-11-07 22:09:05

标签: java

每次输入String或Char时,我的read()方法都会崩溃。我怎么能让它只接受整数值。当我输入一个int时,它工作正常但是当我输入一个Char或String时,我得到一个重复的"输入帐户打开的那天: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());
        }
    }
}

3 个答案:

答案 0 :(得分: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.");
}

答案 1 :(得分:1)

我想这是一个功课问题,所以不应该给你确切的答案。但您可以使用以下内容:

if (input.hasNextInt()) {
    int number = input.nextInt() ; 
    System.out.println(number);
    //your code
} else {
    System.out.println("Sorry please enter a number!");
}

有关详细信息,请查看此处:
1. How do I keep a Scanner from throwing exceptions when the wrong type is entered?
2. How to use Scanner to accept only valid int as input

答案 2 :(得分:0)

在这句中"输入帐户开立的日期:null",单词null来自你的catch部分e.getMessage。 如果你想让用户输入数字,当他们键入错误的类型时。

您需要在try部分再次初始化变量。演示代码如下,我已经测试过,它工作正常。

import java.util.Scanner;

public class Question01 {

    public static void main(String[] args) {

        // new Scanner(System.in)
        boolean success = false;
        Object d = null;
        while (!success) {
            try {

                System.out.print("Enter the day the account opened: ");
                Scanner keyboardIn = new Scanner(System.in);
                d = keyboardIn.nextInt();

                System.out.println(d);

                success = true;
            } catch (Exception e) {

                System.out.println("Error");
                // keyboardIn.close();
            }
        }

    }
}