Marky0414
Marky0414

Reputation: 73

BufferedReader readLine() from standard input

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.

Upvotes: 6

Views: 22519

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213223

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.

Upvotes: 6

Related Questions