Java matrix not printing last line

package com.test;
import java.util.Scanner;

public class Main {

    public static void main(String args[]) {
        System.out.println("Rows = ?");
        Scanner sc = new Scanner(System.in);
        if(sc.hasNextInt()) {
            int nrows = sc.nextInt();
            System.out.println("Columns = ?");
            if(sc.hasNextInt()) {
                int ncolumns = sc.nextInt();
                char matrix[][] = new char[nrows][ncolumns];
                System.out.println("Enter matrix");
                for (int row = 0; sc.hasNextLine() && nrows > row; row++) {
                        matrix[row] = sc.nextLine().toCharArray();
                }
                for (int row = 0; row < nrows; row++) {
                    for (int column = 0; column < matrix[row].length; column++) {
                        System.out.print(matrix[row][column] + "\t");
                    }
                    System.out.println();
                }
            }
        }
    }
}

      

So my program reads the matrix and prints it, but the last line doesn't print. I think this problem is in a for-loop that prints columns.

Input:

2
2
-=
=-

      

Actual output:

-=

      

Expected Result:

-=
=-

      

+3


source to share


1 answer


You need to change

for (int row = 0; sc.hasNextLine() && nrows > row; row++) {
        matrix[row] = sc.nextLine().toCharArray();
}

      

to

sc.nextLine();
for (int row = 0; nrows > row; row++) {
        matrix[row] = sc.nextLine().toCharArray();
}

      

The main problem is that nextInt()

or other methods nextXXX()

besides nextLine()

do not consume line separators, which means that when typing 2

(and pressing enter), the actual input will look like 2\n

or 2\r\n

or 2\r

depending on the OS.

So when nextInt

you only read the value 2

, but the scanner cursor will be positioned before the line separators, like

2|\r\n
 ^-----cursor

      



which will make it nextLine()

return an empty string because there are no characters between the cursor and the next line separators.

So, to actually read the line after nextInt

(and not the empty line), you need to add another one nextLine()

to position the cursor after those line separators.

2\r\n|
     ^-----cursor - nextLine() will return characters from here 
                    till next line separators or end of stream

      


By the way, to avoid this problem, you can use

int i = Integer.parseInt(sc.nextLine());

      

instead of int i = nextInt()

.

+3


source







All Articles