I need to read from the standard input. I am not that familiar with BufferedReader and have only used Scanner so far. Scanner (or probably something inside my code) keeps on giving me TLE. Now the problem is that BufferedReader seems to skip some lines and I keep on getting a NumberFormatException.
Here's my code:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(reader.readLine());
for(int i = 0; i < cases && cases <= 10; i++) {
int numLines = Integer.parseInt(reader.readLine());
String[] lines = new String[numLines + 1];
HashSet<String> pat = new HashSet<String>();
for(int j = 0; j < numLines && j <= 10; j++) {
String l = reader.readLine();
String patternStr = "\\W+";
String replaceStr = "";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(l.toString());
String m = matcher.replaceAll(replaceStr);
lines[j] = m;
getPatterns(m, pat);
System.out.println(m);
}
The error occurs after the second input. Please help.
BufferedReader readLine() method in Java with Examples Return value: This method returns the String that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL.
Reading User's Input using BufferedReader class:By wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line. Here's an example: BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.
Class BufferedReader. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
BufferedReader#readLine()
method does not read the newline character at the end of the line. So, when you call readLine()
twice, the first one will read your input, and the second one will read the newline
left over by the first one.
That is why it is skipping the input you gave.
You can use BufferedReader#skip()
to skip the newline character after every readLine
in your for loop
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With