问题是二维数组和对称性

时间:2017-09-23 17:02:29

标签: java arrays io

我正在解决当前项目的问题,试图找出如何创建矩阵并查看它是否对称。我还需要显示它包含多少行以及它有多少列。

输入文件包含数字:

3
8 5 -6 7
-19 5 17 32
3 9 2 54

到目前为止,这是我的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class MatrixSymmetry {

public static void main(String[] args) throws FileNotFoundException {

        File f = new File("testwork.txt");
        Scanner in = new Scanner(f);
        int numRows = in.nextInt();

        ArrayList<Integer> columnCheck = new ArrayList<Integer>();
        int numColumns = 0;

        while (in.hasNextLine()) {  
            Scanner scnr = new Scanner(in.nextLine());
            numColumns++;

            while (scnr.hasNextInt()) {
                columnCheck.add(scnr.nextInt());
            }
            scnr.close();
        }

        while (in.hasNext()) {
            String matrix = in.nextLine();
            Scanner matrixScan = new Scanner(matrix);

            int[][] numArray = new int[numRows][numColumns];

            for (int i = 0; i < numRows; i++) {

                for (int j=0; j < numColumns; j++) {

                    numArray[i][j] = matrixScan.nextInt();

                    if (numArray[i][j] == numArray[j][i]) {
                        System.out.println("The Matrix is Symmetric");
                    }
                    else {
                        System.out.println("The Matrix is not Symmetric");
                    }
                }
            }
            matrixScan.close();
        }
        System.out.println("Number of rows: " + numRows + 
                        "\nNumber of columns: " + numColumns);
            in.close();
    }
}

我收到的输出是:

Number of rows: 3
Number of columns: 4

我错过了什么/做错了什么?

1 个答案:

答案 0 :(得分:0)

在第二个while中,您的in已到达文件末尾,hasNext()将返回false。