Search code examples
javainputbufferedreader

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?


Solution

  • Try this,

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

    this is faster than string.split();