Problems with nextLine ();
Possible duplicate:
Problem with scanner when using nextLine after nextInt
I am trying to create a program where it allows the user to enter values ββinto an array using a scanner.
However, when the program asks the student for the next relative, he does not allow the user to enter anything and immediately ends the program.
Below is the code I made:
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 tried using next (); but it will just take the first word of user input, which is not what I wanted. Is there a way to solve this problem?
source to share
The problem occurs when you press the enter key, which is a newline character \n
. nextInt()
consumes only an integer but skips a newline \n
. To work around this issue, you may need to add an extra input.nextLine()
after reading int
that might consume \n
.
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();.
// rest of the code
source to share
The problem is input.nextInt()
, this function only reads the int value. So when you continue to read with input.nextLine()
, you get the "\ n" key Enter. Therefore, to skip this, you must add input.nextLine()
.
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Why next()
doesn't it work ..?
next () returns the next token and nextLine () returns NextLine. It's good if we know the difference. The token is a string of nonblank characters surrounded by spaces.
From Doc
Finds and returns the next complete token from this scanner. The first token is preceded by an input that matches the delimiter pattern. This method may block while waiting for input to scan, even if the previous call to hasNext () returned true.
source to share