Entering buffer space with a space

At the beginning I would like to mention that I am not very good at java and I was looking for StackOverFlow to solve my problem and either I didn't find it or didn't understand the answer, so I am asking now

I felt like getting started with BufferedReader and couldn't find any tutorial I understood, so I took a bit from here and there and wrote this example:

BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
int x = Integer.parseInt(input.readLine());
String y = input.readLine();
System.out.println(x);

      

this code worked for input 34

then enter abc

but with what i am trying to achieve i need 34 abc

space separated input to input together and what x

will get 34

and y

get abc

. this will work when using a scanner, but the problem is that the Scanner is taking the time I am doing because it is slow.

Is there any easy way to get input space like there was with Scanner?

+3


source to share


5 answers


Try it,

StringTokenizer tk = new StringTokenizer(input.readLine());
int m = Integer.parseInt(tk.nextToken());
String s = tk.nextToken();

      



it's faster than string.split ();

+5


source


If you want to read 2 values ​​from one string, you cannot parse the whole string to Integer. This gives the NumberFormatException.

Read the string first, then split it by ' '

and then parse the 1st part to Integer.



String line = reader.readLine();
String splitLine = line.split(" ");
Integer x = Integer.parseInt(splitLine[0]);
String y = splitLine[1];

      

0


source


String line = input.readLine();
String []tokens = line.split(" ");
int x = Integer.parseInt(tokens[0]);
String y = tokens[1];

      

Split the input with a function split()

and access it from the array

0


source


If you were unable to use the function String.split()

on input.readLine()

?

String line = input.readLine();


int x = Integer.parseInt(line.split(" ")[0]);

0


source


You can read multiple integers on the same line, separated by spaces, like: 1 5 5; using the following example.

StringTokenizer tk = new StringTokenizer(input.readLine());
int a = Integer.parseInt(tk.nextToken());
int b = Integer.parseInt(tk.nextToken());
int c = Integer.parseInt(tk.nextToken());

      

0


source







All Articles