Search code examples
javainputbufferedreader

Java : Error when reading input with BufferedReader


I'm working with Java to interpret some input. And I'm using BufferedReader. My goal is to read an amount number of lines after reading a char, where -1 is the stop command. Something like this

2
CASE 1 - L1
CASE 1 - L2
3
CASE 2 - L1
CASE 2 - L2
CASE 2 - L3
-1

My goal would be have as an output just :

CASE 1 - L1
CASE 1 - L2
CASE 2 - L1
CASE 2 - L2
CASE 2 - L3

What would mean that I'm getting the lines in the right way. My code is as follows:

public class TESTE {

    public static void main(String[] args) throws IOException {
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        int state;

        while ((state = buffer.read()) != 45) {
            char c = (char) state;
            if (Character.isDigit(c)) {
                int n = Character.getNumericValue(c);
                for (int i = 0; i < n; ++i) {
                    System.out.println("L:" + buffer.readLine());
                    System.out.println();
                }
            }
        }

    }

}

For some reason my output is:

L:
L:CASE 1 - L1
L: - L2
L:
L:CASE 2 - L1
L:CASE 2 - L2
L: - L3

What am I doing wrong ? Is there an elegant way to deal with that Input ?


Solution

  • Here's what happened.

    1. buffer.read() returns 50 which is '2'
    2. Convert it to n, which is 2
    3. Read two lines

    Now what's next in the buffer at this point? A \n right after '2'! That's why you get your first output

    L:
    

    An Empty Line.

    Well there's no point to continue. The whole process is broken.

    One way to do it:

        Scanner in = new Scanner(System.in);
        while (true) {
            int n = Integer.parseInt(in.nextLine());
            if (n == -1) break;
            for (int i = 0; i < n; i++) {
                System.out.println("L:" + in.nextLine());
            }
        }