1

I am trying to get the input from scanner and assign the value into a String array And the loop has to run for 3 times abut it's taking only two inputs. can anyone please explain why this is not taking 3 inputs and displaying the same.

import java.util.Arrays;
import java.util.Scanner;

public class DimentionalArray {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt(); // ex, if size is 3 
        String[] str = new String[size];

        for (int i = 0; i < str.length; i++) {
            str[i] = sc.nextLine(); 
        }
        Arrays.stream(str).forEach(e -> {System.out.println(e);});
    }
}

For example. my inputs are

3 //size
1 2 // 1st input 
3 4 //2nd input 
4 5 // 3rd input 

but it's not reading the input and its getting closed after reading the 2nd input(3 4). Can anyone please explain why is this not reading the third element.

Johannes Kuhn
  • 12,878
  • 3
  • 41
  • 66
Hiro
  • 11
  • 2
  • 1
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Johannes Kuhn Nov 20 '19 at 18:50

1 Answers1

2

Just add

sc.nextLine(); 

after the int size = sc.nextInt();

Varun Mukundhan
  • 250
  • 1
  • 8