【问题标题】:Issue with a two-dimensional array and symmetry二维数组和对称性问题
【发布时间】:2017-09-23 17:02:28
【问题描述】:

我当前的项目有一个问题,我试图弄清楚如何创建一个矩阵并查看它是否对称。我还需要显示它包含多少行以及它有多少列。

输入文件有数字:

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

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

【问题讨论】:

  • 不只是发布代码,你能解释一下你是做什么的吗?那样会更容易阅读,例如通过添加解释某些行后面的意图的 cmets。
  • 第二个 while 看起来似乎无法到达。就在那里尝试的内容而言,它也不可读。
  • 欢迎来到 Stack Overflow!您在问题中发布了很多代码,这使我们(以及未来的读者)不清楚问题出在哪里。请将您的问题代码减少到 10 行或更少。请参阅:How to create a Minimal, Complete, and Verifiable exampleHow to Debug Small Programs
  • 3x4 矩阵如何对称?

标签: java arrays io


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2012-09-13
    • 2019-08-08
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多