0

I have a problem with my scanner and nextLine. What happens is that it skips the first lap of the loop. My guess is that the scanner already contains something here, like a line break or something. It did work if I used two different scanners for the strCount and the one in the loop. Is this right and if it is, is there any way I can make this work without using two different scanners.

import java.util.*;

public class chars_in_string {
public static void main(String[] args) {
    Scanner key = new Scanner(System.in);

    System.out.print("Number of strings?");
    int strCount = key.nextInt();
    String [] array = new String[strCount];

    for(int x = 0; x < strCount; x++){

        System.out.print("String "+(x+1)+":");
        array[x] = key.nextLine();

    }
}

}

Example of the input/output:

Number of strings? 8

String 1:String 2:

From here it works fine to enter any string and it will just jump 1 step in the loop to get the next one.

A.collin
  • 25
  • 4

1 Answers1

4

The problem is that Scanner.nextInt() does not consume the line terminator. Just do an extra nextLine() before entering the loop.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 1
    @user2225454, if this fixed your problem, you should accept Ted's solution as correct (click the check mark) – David K Mar 29 '13 at 20:16