Java Matrix 不打印最后一行


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() 或其他nextXXX()方法(nextLine()除外(不使用行分隔符,这意味着当您输入2(并按回车键(时,实际输入将看起来像2n2rn2r具体取决于操作系统。

因此,使用nextInt您只读取值2但扫描仪的光标将在行分隔符之前设置,例如

2|rn
 ^-----cursor

这将使nextLine()返回空字符串,因为光标和下一行分隔符之间没有字符。

因此,要实际读取nextInt行(不是空字符串(,您需要添加另一个nextLine()以在这些行分隔符之后设置光标。

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

顺便说一句,为了避免这个问题,你可以使用

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

而不是int i = nextInt().

最新更新