Read Space Separated Value in Java

Hello coders, In this blog, we will learn how to take inputs from the user and the inputs are separated by space. If you struggling to take input space-separated values from the user. Then, this blog is for you.

Input :

1 2 3 4 5

Output:

1 2 3 4 5

We will check whether the input has been taken in the same order or not.

So, this can be done in two ways either you can use the Scanner class or BufferedReader class.

First, we will see how to take inputs using the Scanner class. If you are working with java you must be knowing about this Scanner class.

Read Space Separated Value in Java using Scanner Class

import java.util.Scanner;
public class Main
{
	public static void main(String[] args) {
	    Scanner sc=new Scanner(System.in);
	    int n=sc.nextInt();
	    int arr[]=new int[n];
	    for(int i=0;i<n;i++){
	        arr[i]=sc.nextInt();
	    }
	    
	    for(int i=0;i<n;i++){
		System.out.print(arr[i]+" ");
	    }
	}
}


R

Read Space Separated Value in Java using BufferedReader

import java.io.BufferedReader;
import java.util.Scanner;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{
	public static void main(String[] args) throws IOException{
	    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	    Scanner sc=new Scanner(System.in); // using Scanner class for declaring array size
	    int n=sc.nextInt();
	    String [] strNums;
	    int arr[]=new int[n];
	    strNums=br.readLine().split(" ");
	    for(int i=0; i<strNums.length;i++){
	        arr[i]=Integer.parseInt(strNums[i]);
	    }
	    
	    
	    for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]); //Printing the elements
        }
	}
}

If you are working with large inputs always use BufferedReader class. This is much faster than the Scanner class for large inputs.

Leave a Comment