Home » Java » Java program skips asking for user input-Exceptionshub

Java program skips asking for user input-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to ask the user for a date and a time. In my program I have methods to ask the user for these values and methods to validate the inputs. However in my program, the user is never able to input the date value, as the program continues past that point and takes a null value for the date. Why is this? As a result the validation methods cause an error:

java.lang.NullPointerException

“Main”

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

Ask For Date Method

    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");
        }
    }
}

Validate Date method

    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;
}

Get Input Method

    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;
};
How to&Answers:

The reason your program skips the user input is because you are initializing String value = null in your getUserInput()method and then effectively saying while null != null which is false and thus your while loop never executes. I would modify the code like this:

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

while(value.equals("")) {

    try {
        value = input.readLine();
    }

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

Then if the user just spams enter without typing anything it will continuously promt him to enter something.