Abhirup Banerjee
Abhirup Banerjee

Reputation: 33

Input integers in an array from users in Java separated by whitespace

I am solving a practise question in a Java programming website which requires me to input all the necessary integers separated only by a white space where the first number denotes the number of elements in the array and the subsequent numbers should be inserted into the array.

For example,

I want to input in the following manner:-

4 3 1 2 7

Here 4 is the number of elements in the array and 3, 1, 2 and 7 should be inserted into an array.

I am using a scanner class for the same and the code which I am writing is as follows:-

Scanner sc = new Scanner (System.in);
int [] arr = new int [10000];
int n = sc.nextInt();
for (int i=0;i<n;i++)
    arr [i] = sc.nextInt();

But when I am executing the code it is giving NoSuchElementException in the line arr [i]=sc.nextInt(); and it is not executing further.

Can anyone please help me with this?

Upvotes: 3

Views: 105

Answers (1)

Ravi Singh Lodhi
Ravi Singh Lodhi

Reputation: 2793

Try using this:

import java.util.*;
import java.io.*;

public static void main(String[] args) throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String[] input = reader.readLine().split(" ");
    int[] numbers = new int[input.length - 1];
    for(int i = 0; i < numbers.length; i++) {
        numbers[i] = Integer.parseInt(input[i+1]);
    }

    System.out.println("Array = "+Arrays.toString(numbers));

}

Input:

4 1 2 3 4

Output:

Array = [1, 2, 3, 4]

Upvotes: 1

Related Questions