The Simple, Infamous Line-Skipping ".nextLine()" Method
Evening, everyone. I'm sure experienced programmers are familiar with this frustrating issue, and I've searched the web for the solution but couldn't find any correction for what I was working with..
I'm working on a program that asks the user to enter the names of students in an array.. It's also in a for loop. Everything is working but when I get to the part where it asks for their names, it skips it.. Here's the code
Code:
import java.util.*;
public class ClassList
{
public static void main (String[]args)
{
int numStudents;
Scanner input = new Scanner(System.in);
System.out.print ("Enter number of students:");
numStudents = input.nextInt();
String[] name = new String[numStudents];
String[] number = new String[numStudents];
Student s = new Student(name, number);
for (int i = 0; i < numStudents; i++)
{
System.out.print ("Enter student name:");
name[i] = input.nextLine();
System.out.print ("Enter student number:");
number[i] = input.nextLine();
}
System.out.println ("\n\t STUDENT ROSTER\n");
System.out.println ("NAME \t\t\t STUDENT NUMBER");
for (int i = 0; i < numStudents; i++)
{
System.out.println(s.getName()[i] + "\t\t" + s.getNumber()[i]);
}
}
}
The problem is on line 21. While running the program, it will completely skip "Enter Name" and go straight to "Enter number". This happens the first time of the loop, the 2nd and onward times it works fine. Anyone know why this is happening and have a solution to this curse?
Re: The Simple, Infamous Line-Skipping ".nextLine()" Method
I just posted basically the same question, but I'm kind of a newbie so I don't know.
Re: The Simple, Infamous Line-Skipping ".nextLine()" Method
Every time you call input.nextInt() follow it with input.nextLine() so that the end of line token is swallowed.
For example, change this:
Code:
System.out.print ("Enter number of students:");
numStudents = input.nextInt();
to this:
Code:
System.out.print ("Enter number of students:");
numStudents = input.nextInt();
input.nextLine();
Re: The Simple, Infamous Line-Skipping ".nextLine()" Method
Quote:
Originally Posted by
atac57
I just posted basically the same question, but I'm kind of a newbie so I don't know.
Same for you, but you would call scan.nextLine(); after every call to scan.nextDouble() for the same reason.
Re: The Simple, Infamous Line-Skipping ".nextLine()" Method
Ah, you're right, it works fine. I wonder why that glitch occurs, but I'm glad the solution works. Thanks, Fubarable.