anonymous anonymous - 1 month ago 16
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

Answer

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(System.in));
String[] inputStream = bufferedReader.readLine().split(" ");

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

Second Method:-

This method is shorter but less efficient than using BufferedReader.

// Code
Scanner sc = new Scanner(System.in);
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(System.in));
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());
}