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();
}
}
}
}
}
所以我的程序读取矩阵并打印它,但最后一行不打印。我认为,打印列的 for 循环中的问题。
输入:
2
2
-=
=-
实际输出:
-=
预期输出:
-=
=-
最佳答案
你需要改变
for (int row = 0; sc.hasNextLine() && nrows > row; row++) {
matrix[row] = sc.nextLine().toCharArray();
}
到
sc.nextLine();
for (int row = 0; nrows > row; row++) {
matrix[row] = sc.nextLine().toCharArray();
}
主要问题是 nextInt()
或除 nextLine()
之外的其他 nextXXX()
方法不使用行分隔符,这意味着当您输入 2
(并按回车键)时,实际输入看起来像 2\n
或 2\r\n
或 2\r
取决于操作系统。
因此,对于 nextInt
,您只读取值 2
,但 Scanner 的光标将设置在行分隔符之前,例如
2|\r\n
^-----cursor
这将使 nextLine()
返回空字符串,因为光标和下一行分隔符之间没有字符。
所以要实际读取 nextInt
之后的行(不是空字符串),您需要添加另一个 nextLine()
以在这些行分隔符之后设置光标。
2\r\n|
^-----cursor - nextLine() will return characters from here
till next line separators or end of stream
顺便说一下,你可以使用
来避免这个问题int i = Integer.parseInt(sc.nextLine());
代替 int i = nextInt()
。
关于Java Matrix 不打印最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25920326/