BufferedReader readLine () from standard input

I need to read from standard input. I am not familiar with BufferedReader and so far have only used Scanner. The scanner (or probably something inside my code) continues to give me TLE. Now the problem is that the BufferedReader seems to skip some lines, and I keep getting a NumberFormatException.

Here is 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 entry. Please, help.

+4
source share
1 answer

BufferedReader#readLine() method does not read a newline at the end of a line. Therefore, when you call readLine() twice, the first will read your input, and the second will read newline left by the first.

That's why it skips the input you entered.

You can use BufferedReader#skip() to skip the newline after each readLine in the for loop .

+5
source

All Articles