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 programm reads matrix and prints it, but the last row doesn't prints. I think, that problem in for-loop, which prints columns.
Input:
2
2
-=
=-
Actual output:
-=
Expected output:
-=
=-
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();
}
Main problem is that nextInt(), or other nextXXX() methods except nextLine() do not consume line separators, which means that when you input 2 (and press enter) actual input will look like 2\n or 2\r\n or 2\r depending on OS.
So with nextInt you are reading only value 2 but Scanner's cursor will be set before line separators like
2|\r\n
^-----cursor
which will make nextLine() return empty String, because there ware no characters between cursor and next line separators.
So to actually read line after nextInt (not the empty string) you need to add another nextLine() to set cursor after these line separators.
2\r\n|
^-----cursor - nextLine() will return characters from here
till next line separators or end of stream
BTW to avoid this problem you can use
int i = Integer.parseInt(sc.nextLine());
instead of int i = nextInt().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With