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