【问题标题】:Java program skips asking for user inputJava 程序跳过询问用户输入
【发布时间】:2020-02-18 10:43:14
【问题描述】:

我正在尝试向用户询问日期和时间。在我的程序中,我有方法要求用户提供这些值和方法来验证输入。但是在我的程序中,用户永远无法输入日期值,因为程序继续超过该点并为日期取一个空值。为什么是这样?因此,验证方法会导致错误:

java.lang.NullPointerException

“主要”

    public void bookAppointment(BankClient bc) {
    String date = askForDate();
    String time = askForTime();
    sendAppointmentNotification(createAppointmentNotification(date,time));
}

询问日期方法

    private String askForDate() {
    GetInputFromUserInter input = new GetInputFromUser();
    while(true) {
        String date = input.getUserInput("Date For Appointment in the form of DD/MM/YYYY");
        date.trim();
        if (validateDate(date)) {
            return date;
        }
        else {
            System.out.println(date+" is Invalid Date format");
        }
    }
}

验证日期方法

    private static boolean validateDate(String date) {
    System.out.println("here");
    SimpleDateFormat sdfrmt = new SimpleDateFormat("DD/MM/YYYY");
    sdfrmt.setLenient(false);
    try{
            Date javaDate = sdfrmt.parse(date);
    }
        /* Date format is invalid */
    catch (ParseException e){
        return false;
    }
    /* Return true if date format is valid */
        return true;
}

获取输入法

    static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public String getUserInput(String label) {
    String value = null;
    System.out.println( "\nProvide " + label + ":" );
    System.out.println( ">" );

    while(value !=null) {

        try {
            value = input.readLine();
        }

        catch (IOException ex) { ex.printStackTrace(); }            
    }
    return value;
};

【问题讨论】:

  • while(value !=null),你在上面写了value = null4 行
  • 请使用 DateTimeFormatter 而不是 SimpleDateFormat
  • 另外,每次您要求输入时,您都会打开一个新的 BufferedReader 而不会关闭它。
  • @NomadMaker 缓冲区是静态的。只有一个。
  • 抱歉,没注意到。

标签: java input


【解决方案1】:

您的程序跳过用户输入的原因是因为您在getUserInput() 方法中初始化String value = null,然后有效地说while null != null 这是错误的,因此您的while 循环永远不会执行。我会像这样修改代码:

String value = "";
System.out.println( "\nProvide " + label + ":" );
System.out.println( ">" );

while(value.equals("")) {

    try {
        value = input.readLine();
    }

    catch (IOException ex) { ex.printStackTrace(); }            
}
return value;

然后,如果用户只是垃圾邮件输入而没有输入任何内容,它将不断提示他输入内容。

猜你喜欢
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2016-04-26
  • 1970-01-01
相关资源
最近更新 更多