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?
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.
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.
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.
Try this,
StringTokenizer tk = new StringTokenizer(input.readLine());
int m = Integer.parseInt(tk.nextToken());
String s = tk.nextToken();
this is faster than string.split();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With