1

I came across this question and want to recreate it but fill it with an array of strings instead of integers. I want to use arrays and not ArrayList just because I am a beginner and would like to practice more with arrays. I pretty much copied the code but I keep getting an error in the output. Here is my code:

Scanner input = new Scanner(System.in);
    System.out.print("Enter number of arrays: "); 
    int x = input.nextInt();
    String [][] array = new String[x][0]; 

    for(int i = 0; i < x; i++){
       System.out.print("Enter number of elements for array: ");
       int s = input.nextInt();
       array[i] = new String[s]; 

       for(int j = 0; j < s ; j++){ 
          System.out.print("Enter string: ");
          String word = input.nextLine();
          array[i][j] = word;
       }
    }

My output is:

Enter number of arrays: 2
Enter number of elements for array: 3
Enter string: Enter string: hello
Enter string: hi
Enter number of elements for array: 2
Enter string: Enter string: goodbye

Why does it print "Enter string" twice every time? The logic makes sense to me so I'm not sure whats causing the wrong output. Is it the for loop or just the way strings work? Explanation and help with the code would be appreciated. Thanks

dollaza
  • 213
  • 3
  • 9

2 Answers2

1

The logic is correct, but the nextInt() method reads only the number and not the 'enter' character you type after it, so when you call then the nextLine() method, the first time in your loop it reads that 'enter' character, the second reads your input and so the third. To avoid this problem, you can call a nextLine() just after the nextInt(), without assigning it to a variable, so thath it reads the pending character:

 for(int i = 0; i < x; i++){
   System.out.print("Enter number of elements for array: ");
   int s = input.nextInt();
   input.nextLine();
   array[i] = new String[s]; 

   for(int j = 0; j < s ; j++){ 
      System.out.print("Enter string: ");
      String word = input.nextLine();
      array[i][j] = word;
   }
Spock
  • 315
  • 2
  • 13
1

The problem is just that input.nextInt() doesn't grab the newline. If you just stick input.nextLine() after each of the input.nextInt() lines, it should work.

Benjamin Berman
  • 521
  • 4
  • 15