#StringTokenizer isn't letting me use multi-line inputs

1 messages · Page 1 of 1 (latest)

stray vault
#

I'm using a bufferedreader and stringtokenizer to get some inputs, but the string tokenizer keeps processing it early and returning a NoSuchElement exception.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter(System.out);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        System.out.println(n);
        String[] tokens = new String[n];
        for(int i = 0; i < n; i++) {
            tokens[i] = st.nextToken();
            System.out.println(tokens[i]);
        }
        
        pw.println(Arrays.toString(tokens));
        pw.close();
    }
}

I tried using a thread.sleep at the start and in the for loop but it doesnt work either. If I try using a while (st.countTokens() < n) loop, it freezes up and doesnt run either.
This is my input:
3
1 2 1
3 2 1
1 3 1

And this is my error message:

3                                                                          
1 2 1
3 2 1
3
Exception in thread "main" java.util.NoSuchElementException
        at java.base/java.util.StringTokenizer.nextToken(StringTokenizer.java:347)
        at Main.main(Main.java:17)
PS C:\Users\red> 1 3 1^C
cerulean ledgeBOT
#

<@&987246399047479336> please have a look, thanks.

upbeat glade
#

u created the tokenizer on a single line of ur input

#

when u write sth like, it wont be "dynamically linked" or anything

#

as in, it wont execute br.readLine() each time u ask for input

#

thats not a thing

#

instead, it calls br.readLine() at the very moment this line of code is executed

#

and then puts that single String line it read into the tokenizer

#

like new StringTokenizer("3");

#

and thats it

#

it will never read any more lines ever

#

this part of ur logic has to be put into a loop

#

so that it can be repeated per line

#

u should also use the br to read the first number as well

#
int n = Integer.parseInt(br.readLine());
#

and then ud make a "for each line" loop:

#
for (int i = 0; i < n; i++) {
  String line = br.readLine();
  ...
}
#

at that point, u can create ur tokenizer to parse this particular single line