2

In part of my java program I read a sequence of inputs for the user.

Scanner in = new Scanner(System.in);
System.out.println();
System.out.print("Enter student name: ");
String nameParameter = in.nextLine();
System.out.print("Enter student number: ");
int studentNoParameter = in.nextInt();
System.out.print("Enter subject: ");
String subjectParameter = in.nextLine();
System.out.print("Enter level: ");
int levelParameter = in.nextInt();
int[] resultsParameter;
resultsParameter = new int[3];
System.out.println("Enter results (0 if not taken yet)...");
System.out.print("First year: ");
resultsParameter[0] = in.nextInt();
System.out.print("Second year: ");
resultsParameter[1] = in.nextInt();
System.out.print("Third year: ");
resultsParameter[2] = in.nextInt();
System.out.println();

The program compiles, however the line:

String subjectParameter = in.nextLine();

after the prompt to enter Subject, is seemingly skipped in runtime.

Instead of my output being:

Enter Subject: [User Input]

Enter Level: [User Input]

It comes out as:

Enter Subject: Enter Level: [User Input]

The following input is assigned to levelParameter, and an error results if you input something other than an integer, so it seems that the line of code has simply been skipped.

I'm very much a java novice and I'm rather confused. I know this is going to turn out to be something really simple and silly in the end though. Thank you in advance for your time.

HellaWiggly
  • 157
  • 2
  • 6

1 Answers1

3

That's because after reading the int, the rest of the line (which is empty) is still unread and the next call to read nextline() will read the empty line.

So when

int studentNoParameter = in.nextInt(); 

is executed, you enter the int and you hit enter, which creates a '\n' as input. The next call:

in.nextLine(); 

continues to read the rest of the line after the int, which is empty, and it encounters '\n' and terminates.

Adriaan Koster
  • 14,226
  • 4
  • 41
  • 56
lynnyilu
  • 573
  • 1
  • 5
  • 15
  • Oh! I see. I didn't realise that nextInt and nextLine worked like that. Thank you. – HellaWiggly Dec 09 '11 at 05:32
  • 1
    you'll welcome :) just use one more nextline() to get ride of the empty end – lynnyilu Dec 09 '11 at 05:33
  • 2
    @user1089092 If the answer was satisfactory it's a nice gesture to accept the answer. That gives the answerer better reputation and will also improve the chance for you to get answers in the future. – Roger Lindsjö Dec 09 '11 at 08:03
  • Sorry. It was my first time using this website and I didn't notice that feature straight away. ^^ – HellaWiggly Dec 10 '11 at 20:23