【问题标题】:Java Matrix doesn't prints last rowJava Matrix 不打印最后一行
【发布时间】:2014-09-18 18:55:47
【问题描述】:
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 循环中没有正确填充变量。
  • 您确定此代码matrix[row] = sc.nextLine().toCharArray(); 符合您的要求吗?您想在这里实现什么目标?
  • @Pshemo 是的,我确定

标签: java for-loop matrix


【解决方案1】:

你需要改变

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\n2\r\n2\r 取决于操作系统。

所以使用nextInt,您只能读取值2,但扫描仪的光标将设置在像

这样的行分隔符之前
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()

【讨论】:

  • nextInt() 不会消耗换行符,你需要一个 nextLine 来做到这一点。
猜你喜欢
  • 2023-03-28
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
相关资源
最近更新 更多