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.

1

1 Answer 1

2

Just add

sc.nextLine(); 

after the int size = sc.nextInt();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.