2017-09-23 87 views
-2

我有我的當前項目試圖找出如何創建一個矩陣,看看它是否是對稱的問題。我還需要顯示它包含的行數和它有多少列。問題與二維陣列和對稱

輸入文件的數字:

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 

我在想什麼/做錯了?

+0

而不是隻發佈代碼,你能解釋你做了什麼嗎?比較容易閱讀,例如添加解釋某些行背後意圖的註釋。 – Zabuza

+0

第二次雖然看起來不可見。此外,它在那裏試用的內容不可讀。 – nullpointer

+0

歡迎來到Stack Overflow!你已經在你的問題中發佈了很多代碼,這使得我們(以及未來的讀者)不清楚問題出在哪裏。請將您的問題代碼減少到10行或更少。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)和[如何調試小程序](https://ericlippert.com/2014/03/05 /如何調試的小程序/)。 –

回答

0

在第二個while中,您的in已到達文件末尾,hasNext()將返回false。