How to Take Input From User Separated By Space in Java ?
Last Updated :
01 Feb, 2023
There are 2 methods to take input from the user which are separated by space which are as follows:
- Using BufferedReader Class and then splitting and parsing each value
- Using nextInt( ) method of Scanner class
Let us discuss both the methods one by one in order to get a better understanding by implementing the same clean java programs.
Method 1:
Using BufferedReader Class and then splitting and parsing each value.
Procedure:
- Using readline() method of BufferedReader and Scan the whole string.
- Split this String for str.split(” “)
- Iterate over the above array and parse each integer value using Integer.parseInt( ).
Example
Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class GFG {
public static void main(String[] args)
throws IOException
{
BufferedReader bi = new BufferedReader(
new InputStreamReader(System.in));
int num[] = new int [ 10 ];
String[] strNums;
System.out.println( "enter string of numbers" );
strNums = bi.readLine().split( " " );
for ( int i = 0 ; i < strNums.length; i++) {
num[i] = Integer.parseInt(strNums[i]);
}
System.out.println( "printing stored numbers " );
for ( int i = 0 ; i < strNums.length; i++) {
System.out.println(num[i]);
}
}
}
|
Output:
FIG = OUTPUT OF METHOD 1
Method 2: Using nextInt() method of Scanner class.
Procedure:
- Using the nextInt() method of Scanner class and scan to scan the input.
- Using for loop to store input in an array.
- Iterate through the above array and parse each integer using sc.nextInt()
Example
Java
import java.io.IOException;
import java.util.Scanner;
class GFG {
public static void main(String[] args)
throws IOException
{
System.out.println( "enter input " );
Scanner sc = new Scanner(System.in);
int [] nums = new int [ 10 ];
int i;
for (i = 0 ; i < nums.length; i++) {
nums[i] = sc.nextInt();
}
System.out.println( "printing stored values" );
for (i = 0 ; i < nums.length; i++) {
System.out.println(nums[i] + " " );
}
}
}
|
Output:
FIG = OUTPUT OF METHOD 2
Note: The first method using Bufferedreader class and then splitting and parsing each value is much faster than using nixing() method of Scanner class. It is nearly 2 times faster than the second one. Below we do provide in order how to calculate the time consume by both methods by using nanotime method
// Initializing variables
long startTime, endTime;
// Start time
startTime = System.nanoTime(); {
// Insert code here
// Method 1 or method 2 code
}
// End time
endTime = System.nanoTime();
Share your thoughts in the comments
Please Login to comment...