how to accept inputs on same line on console in java??? Plz help…
Use StringTokenizer
available in the java.util
package.
For example, for the sample input given below:
First line contains N
Second line contains N integers
7
12 34 56 78 76 54 32
here is how to use StringTokenizer
import java.util.StringTokenizer;
.
.
.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; ++i) {
arr[i] = Integer.parseInt(st.nextToken());
}
.
.
.
Fore more information on what a StringTokenizer
is, or what it does or what all options are available when using a StringTokenizer
, refer to the Javadoc here: http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
The idea is, you need to break down each of the separate items given on the single line.
The breaking down can be achieved by using delimiters (special characters, that are not part of the input themselves, but is used as a separator). The most common delimiter is the space character.
StringTokenizer
is a class that does this task for you.
using StringTokenizer as answered by @tijoforyou is a good and smooth way. Another way of doing the same thing is :-
.
.
.
java.io.BufferedReader br=new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
int N=Integer.parseInt(br.readLine());
String input[]=(br.readLine()).split(" ");
int arr[]=new int[N];
for(int i=0;i<N;i++)
{
arr[i]=Integer.parseInt(input[i]);
}
…
This will create a string array (‘input’) whose indices will hold every space separated input you gave. Afterwards we simply converted this string format to integer format. (this is almost similar to using StringTokenizer)
ennaku thariadu da .unnaku mathunda thariyuma .ok da .
have a jilaaapi night!!! ha ha ha
ok da
The idea is, you need to break down each of the separate items given on the single line.
The breaking down can be achieved by using delimiters (special characters, that are not part of the input themselves, but is used as a separator). The most common delimiter is the space character.
StringTokenizer is a class that does this task for you.
engalukum therium
Yes, it is apart from the last two words
this code given below will do the same job. it doesn’t matter whether you give input line by line or space separated it will accept input both ways.
import java.util.*;
class test{
public static void main(String[] args) {
Scanner ip = new Scanner(System.in);
int[] arr= new int[5];
int i=0;
while(i!=5){
arr[i]= ip.nextInt();
i++;
}
}