10

Possible Duplicate:
Scanner issue when using nextLine after nextInt

I am trying create a program where it lets the user inputs values into an array using scanner.

However, when the program asks for the student's next of kin, it doesn't let the user to input anything and straight away ends the program.

Below is the code that I have done:

if(index!=-1)
    {
        Function.print("Enter full name: ");
        stdName = input.nextLine();

        Function.print("Enter student no.: ");
        stdNo = input.nextLine();

        Function.print("Enter age: ");
        stdAge = input.nextInt();

        Function.print("Enter next of kin: ");
        stdKin = input.nextLine();

        Student newStd = new Student(stdName, stdNo, stdAge, stdKin);
        stdDetails[index] = newStd;
    }

I have tried using next(); but it will only just take the first word of the user input which is not what I wanted. Is there anyway to solve this problem?

Community
  • 1
  • 1
jl90
  • 599
  • 2
  • 6
  • 23

3 Answers3

23

The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.

Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();.

// rest of the code
leonheess
  • 5,825
  • 6
  • 42
  • 67
Swapnil
  • 7,762
  • 4
  • 34
  • 56
9

The problem is with the input.nextInt() this function only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine().

Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();

Why next() is not working..?
next() returns next token , and nextLine() returns NextLine. It good if we know difference. A token is a string of non blank characters surrounded by white spaces.

From Doc

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

Sumit Singh
  • 23,530
  • 8
  • 71
  • 99
4

Make input.nextLine(); call after input.nextInt(); which reads till end of line.

Example:

Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();  //Call nextLine

Function.print("Enter next of kin: ");
stdKin = input.nextLine();
kosa
  • 63,683
  • 12
  • 118
  • 157