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?
source to share
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];
source to share
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());
source to share