Hiro
Hiro

Reputation: 11

Read a input from Scanner to Array of Strings in java

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.

Upvotes: 1

Views: 843

Answers (1)

Varun Mukundhan
Varun Mukundhan

Reputation: 278

Just add

sc.nextLine(); 

after the int size = sc.nextInt();

Upvotes: 2

Related Questions