Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader space separated input

first I'd like to mention that I am not realy experienced in java, and I searched StackOverFlow for a solution to my problem and either I didn't find it or didn't understand the answer, so I am asking now:

i wanted to start working with BufferedReader and didn't find any guide that i understood propely, so i picked up bits 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 the input 34 then enter then abc, but at what im trying to achieve i need the input 34 abc separated by space to be inputed together and that x will get 34 and y will get abc. this will work when using Scanner, but the problem is Scanner times out the exercise i'm doing because it's slow.

is there any simple way to get those input space separated like it was with Scanner?

like image 844
shaythan Avatar asked Jun 03 '15 08:06

shaythan


People also ask

How do you separate inputs by spaces?

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.

How do you take space separated integer input in python?

To take space-separated integers from user input:Use the input() function to take multiple, space-separated integers. Use the str. split() function to split the string into a list. Use the int() class to convert each string in the list to an integer.

How do you read a space separated string in C++?

Now, how to read string with spaces in C++? We can use a function getline(), that enable to read string until enter (return key) not found.


1 Answers

Try this,

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

this is faster than string.split();

like image 124
Sanira Avatar answered Oct 08 '22 22:10

Sanira