Search code examples
javadatainputstream

Reading data line by line in Java from the input stream


I need to read data of the format:
2
4
7
6 4
2 5 10
9 8 12 2

the data needs to be from the default input stream, System.in. I'm using an InputStreamReader wrapped in a BufferedReader, so I am able to do line by line reading.

InputStreamReader isr=new InputStreamReader(System.in);
    BufferedReader in=new BufferedReader(isr);
    String x=in.readLine();
    int numcase=Integer.parseInt(x);
    for(int i=1;i<=numcase;i++){
        System.out.println("");
        x=in.readLine();
        int n=Integer.parseInt(x);
        int[][]t=new int[n+1][n+1];
        for(int j=1;j<=n;j++){
            System.out.println();
            x=in.readLine();
            StringTokenizer st=new StringTokenizer(x);
            for(int k=1;k<=1;k++){
                x=st.nextToken();
                int nume=Integer.parseInt(x);
                t[j][k]=nume;
            }
        }

the problem is that if the blank System.out.println statement isnt there, it refuses to read in a line of input past reading the first two lines. Thing is, where I'm submitting the code monitors the output stream and as such will grade my output as incorrect by outputting the wrong answer.


Solution

  • I am not sure what you are expecting but writing to system.out has no effect on what you read from system.in.

    That said some pointers about your code:

     String x=in.readLine();
     int numcase=Integer.parseInt(x);
     for(int i=1;i<=numcase;i++){
    

    this loop will be entered twice.

    x=in.readLine();
    int n=Integer.parseInt(x);
    int[][]t=new int[n+1][n+1];
    

    n will be 4 and the array will be of size 5 by 5. Why? I cant understand the reasoning behind this.

     for(int j=1;j<=n;j++){
    

    this loop will be executed 4 times. Reading one line every time.

     StringTokenizer st=new StringTokenizer(x);
            for(int k=1;k<=1;k++){
    

    This loop will always be entered only ONCE even though there may be more than one token.

    int nume=Integer.parseInt(x);
                t[j][k]=nume;
    

    since k is always 1, you will only fill in one of the row/column in your 2d array.

    Conclusion. print statements are doing no magic.

    The code is doing what it is supposed to do.

    Think about what you are attempting to do and print out the values of variables to confirm the behaviour as you code.

    I am pretty sure that you are attempting to fill the 2d array with numbers and the problem lies with the condition over k but since I do not really know what you are trying to do, I cant be 100% sure.

    Edit

    command line