BufferedReader space separated input

18,150

Try this,

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

this is faster than string.split();

Share:
18,150
shaythan
Author by

shaythan

Updated on June 18, 2022

Comments

  • shaythan
    shaythan almost 2 years

    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?

  • shaythan
    shaythan almost 9 years
    thanks a lot! it worked. also, what is this StringTokenizer and where can i learn more about it?
  • shaythan
    shaythan almost 9 years
    thanks. last question though, how do i move to the the next line? like when the input is 23 sdf 35 gtr i need it to jump the line and get the next input from the line below
  • shaythan
    shaythan almost 9 years
    yeah, figured it out eventually, but untill i did i solved th problem with the split method. anyway, many thanks!
  • Aditya P
    Aditya P over 5 years
    line.split will return a String[] so there will be a Type Mismatch.
  • zubergu
    zubergu over 5 years
    Thanks, fixed it.