-1

I'm trying to get the first three characters from a user inputted string but regardless of what I try, the code always results in a IndexOutOfBoundException error.

The code is:

System.out.print("Enter a year: ");
int year = input.nextInt();

System.out.print("Enter a month: ");
String s = input.nextLine();
char ch0 = s.toUpperCase().charAt(0);
char ch1 = s.toUpperCase().charAt(1);
char ch2 = s.toUpperCase().charAt(2);

if (ch0 == 'J') {

    if (ch1 == 'A' && ch2 == 'N') {
        System.out.println("Janruary " + year + " has 31 days."); 
    }

How do I fix this error?

1 Answers1

0

Replace:

String s = input.nextLine();

With:

String s = input.next();

Since nextInt does not consume any whitespace or newline after the read token, that means that if the user enters a number and presses enter, there's still a linebreak in the stream.

So when you call nextLine later it just reads that linebreak and returns the empty string.