-2

I have an "Appointment" class as follows

private String month;
private int day;
private int hour, minute;
private String message;

Appointment() {
    month = "Jan";
    day = 1;
    hour = 12;
    minute = 0;
    message = "message";
}

private void setMonth(String monthIn) {
    if (monthIn.length() > 3) {
        System.out.println("Re-enter and keep month to 3 letters");
    } else {
        month = monthIn;
    }
}

private void setDay(int dayIn) {
    day = dayIn;
}

private void setHour(int hourIn) {
    hour = hourIn;
}

private void setMinute(int minuteIn) {
    minute = minuteIn;
}

private void setMessage(String messageIn) {
    message = messageIn;
}

public void inputAppointment() {
    System.out.println("Input appointment (month, day, hour, minute, message)");
    setMonth(UserInput.getString());
    setDay(UserInput.getInt(1, 31));
    setHour(UserInput.getInt(1, 12));
    setMinute(UserInput.getInt(0, 59));
    setMessage(UserInput.getString());
}

In my main method i have

Appointment app = new Appointment();
app.inputAppointment();

But I'm only able to input the first string and the following 3 integers. setMessage(UserInput.getString()); never executes. The arguments sent to the set methods in inputAppointment() call methods from a "UserInput" class that handles input as follows

public static String getString() {
    return scan.nextLine();
}

public static int getInt() {
    return scan.nextInt();
}

public static int getInt(int min, int max) {
    int input = getInt();
    if (input >= min && input <= max) {
        return input;
    } else {
        System.out.println("Invalid input. Re-enter...");
        return getInt(min, max);
    }
}
  • Without seeing your UserInput class I can't be certain, but this sounds like the issue of using `nextLine()` after using `nextInt()` and consuming the newline without accepting further input - see [this question](http://stackoverflow.com/q/13102045/1828486) for more info. – Mage Xy Mar 07 '16 at 19:51
  • Thanks this link was helpful – Jason Monsalve Mar 07 '16 at 21:25

1 Answers1

0

Every time the user inputs text into the console and presses enter, the user's input plus the end of line characters '\r\n' are added to the input buffer.

scan.nextLine() reads to the next '\r\n' characters and returns what it found.

scan.nextInt() will read ahead until it has scanned in the next int, but it will not consume the '\r\n' from the user pressing enter. After your 3rd call there is still a '\r\n' on the input buffer and your next call to scan.nextLine() assumes this is the user's next line of input.

If you are expecting the user to enter an integer on separate lines, then you need an extra call to scan.nextLine() to consume the end of line characters.

i.e.

public static int getInt() {
    int input = scan.nextInt();
    scan.nextLine();
    return input;
}
spectacularbob
  • 2,719
  • 2
  • 18
  • 36