user2930063
user2930063

Reputation: 25

Skipped Iteration in For Loop in Java

My for loop skips to the 2nd grade to be entered and I cannot figure out why this is happening. The output looks like this:

Type in Grade Number 1: Type in Grade Number 2:

public static void main(String args[]){

    Scanner inputReader = new Scanner(System.in);
    System.out.print("Would you like to input grades?: ");
    String input = inputReader.next();

    if (input.equals("y")){
        String[] grades =new String[2];

        for (int counter = 0; counter < grades.length; counter++){
            System.out.print("Type in Grade Number " + (counter + 1) + ": ");
            grades[counter] = inputReader.nextLine();
        }
     }
}

Upvotes: 1

Views: 108

Answers (2)

JB Nizet
JB Nizet

Reputation: 692201

After

String firstName = inputReader.next();

You must call nextLine(). Indeed, next() doesn't consume the EOL, and thus when you call nextLine() in the first iteration of the loop, it immediately consumes the EOL after the first name.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533880

next() reads a word, not the whole line, and it doesn't throw away the line after that word so when you type the firstname, the Scanner is still waiting for a reason to consume the rest of the line. Only when you call nextLine() for the first time it does that (I am assuming the rest of the line is blank)

Change your code to be

    String lastName = inputReader.nextLine(); // read the whole line, not just a word
    System.out.print("Student First Name: ");
    String firstName = inputReader.nextLine();

Upvotes: 2

Related Questions