Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader readLine() from standard input

Tags:

java

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.

like image 440
Marky0414 Avatar asked Dec 20 '12 06:12

Marky0414


People also ask

What data type does the readLine () method in the BufferedReader class return?

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.

How do you take input from a buffer reader?

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.

How does BufferedReader readLine work?

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.


1 Answers

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.

like image 143
Rohit Jain Avatar answered Oct 18 '22 05:10

Rohit Jain