1
import java.util.Scanner;

public class ClassList {

    static final int SIZE = 10;

    public static void main(String Args[]) {

        Student[] students = new Student[SIZE];
        Scanner s = new Scanner(System.in);

        String name, id;
        float gpa;

        do {

            System.out.println("Enter a Student");
            name = s.nextLine();

            System.out.println("Enter a ID");
            id = s.nextLine();

            System.out.println("Enter a GPA");
            gpa = s.nextFloat();

        } while(!name.equals("quit"));
    }
}

basically, what happened when you run this program is that it will run one fine, then on the 2nd iteration, it will ask for a student name. but it will just skip over where the user should input it and go onto "get ID". How do i stop that.

hologram
  • 501
  • 1
  • 5
  • 20
user1840435
  • 47
  • 1
  • 1
  • 3
  • Consider posting code with just a *little* less white space next time. Your unnecessary open spaces make your code a bit hard to read. Remember, good code formatting is more for our benefit than for yours, but since we can give you better help if we're able to easily read and understand your code, then it's also for your benefit as well. – Hovercraft Full Of Eels Nov 29 '12 at 23:31
  • This question is similar to http://stackoverflow.com/q/6289765/130224 – reprogrammer Nov 29 '12 at 23:38

2 Answers2

3

In the first iteration, nextFloat() doesn't consume any new line characters. In the second iteration, the nextLine() method will consume the newline characters left from the first iteration. As a result, it appears that the nextLine() method in the second iteration skips over user input, while it's just consuming the newline characters left from the previous iteration.

One way to fix this problem is to call nextLine() after nextFloat() to consume the leftover new line character.

reprogrammer
  • 13,350
  • 15
  • 52
  • 91
1

You can place

s.nextLine();

at the end of the loop to consume the newline character. Currently Scanner.getFloat() is passing the newline character through to your statement:

name = s.nextLine();

which is not blocking as it has been supplied with this character.

Reimeus
  • 152,723
  • 12
  • 195
  • 261