Nuances of the Scanner Class

I'm having trouble with the Scanner class... here is a snippet of code from a program I am writing.

==========

1System.out.print("Enter the name of the new passenger-> ");

2String passengerName = scan.nextLine();

3System.out.println(passengerName);

4

5System.out.print("Enter the ticket type (E or F)-> ");

6String desiredClassType = scan.nextLine();

7System.out.println(desiredClassType);

8char desiredClassTypeCode = (desiredClassType.toUpperCase()).charAt(0);

9

10

11System.out.print("Enter the desired row-> ");

12int desiredRow = scan.nextInt();

13System.out.println(desiredRow);

14

15System.out.print("Enter the desired seat-> ");

16String desiredSeat = scan.nextLine();

17System.out.println(desiredSeat);

18char desiredSeatCode = desiredSeat.charAt(0);

19

20System.out.print("Smoking or non-smoking (S or N)-> ");

21String desiredSmoking = scan.nextLine();

22System.out.println(desiredSmoking);

23char desiredSmokingCode = (desiredSmoking.toUpperCase()).charAt(0);

==========

The problem is, after the scan.nextInt() on line 12, the user never gets a chance to enter input for the scan.nextLine() on line 16. The program just plows right on through and returns the following error at line 18:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

If I change the scan.nextLine() in line 16 to scan.next(), it works alright until the next time I call a scan.nextLine at line 21. Then the same error message appears at line 23. Is there something I'm missing? I can't just change everything to scan.next because some inputs require a string that includes whitespace. However, scan.nextLine keeps giving me these errors...?

[1866 byte] By [javabytes87a] at [2007-11-27 1:56:49]
# 1

when the program asks you to enter a number, you enter a number and press enter. The nextInt method reads the number but leaves the line feed. Next, the program calls nextLine. What will it return? It will return the 0-length string from where the number ended until the line feed, and removes the line feed from the stream. This is why the user never gets a chance to enter anything: he's already entered what the program was looking for.

To get rid of the line feed, call nextLine directly after calling nextInt and throw away the return value.

int desiredRow = scan.nextInt();

scan.nextLine(); // throw away rest of line

jsalonena at 2007-7-12 1:31:40 > top of Java-index,Java Essentials,New To Java...