view raw
anonymous anonymous - 7 months ago 60
Java Question

How to take space separated inputs in java?

I am a naive programmer. I want to take space separated integer as input and then store in an array in java. Could you please help me, how can i do that?

Edit - I am writing code for an online coding competition. To check the code the they give input as integers separated by spaces. Ex- 2 5 7 9 11 1 6 8


There are many ways to take space separated inputs in java, but one of the easiest method is to take input as a stream and then separate them into token by using "split()" method. In this way you can break input stream into token whether they are separated by space, hyphen or any other symbol.

First method:-

// Code
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(;
String[] inputStream = bufferedReader.readLine().split(" ");

int[] arr = new int[inputStream.length];
for(int i=0;i<inputStream.length;i++){

Second Method:-

This method is shorter but less efficient than using BufferedReader.

// Code
Scanner sc = new Scanner(;
int arr[] = new int[no_of_inputs];

for(int i=0;i<no_of_inputs;i++){
    arr[i] = sc.nextInt();

Third Method:-

Using StringTokenizer you can break any string into tokens.

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(;
int[] arr = new int[no_of_inputs];

StringTokenizer st = new StringTokenizer(bufferedReader.readLine());
for(int i=0;i<no_of_inputs;i++){
    arr[i] = Integer.parseInt(st.nextToken());