2011-01-22 89 views
3

我在文件'array.txt'中有一個2-D int數組。我試圖讀取二維數組中的文件中的所有元素。我在複製時遇到問題。它顯示所有複製後的值爲'0'的元素代替它們的原始值。請幫幫我。 我的代碼是:從文件中讀取2-D數組

import java.util.*; 
import java.lang.*; 
import java.io.*; 

public class appMainNineSix { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) 
     throws java.io.FileNotFoundException{ 
     // TODO Auto-generated method stub 
     Scanner input = new Scanner (new File("src/array.txt")); 
     int m = 3; 
     int n = 5; 
     int[][] a = new int [m][n]; 
     while (input.next()!=null){ 
      for (int i=0;i<m;i++){ 
       for (int j=0;j<n;j++) 
        a[i][j]= input.nextInt(); 
      } 

     } 
     //print the input matrix 
     System.out.println("The input sorted matrix is : "); 
     for(int i=0;i<m;i++){ 
      for(int j=0;j<n;j++) 
       System.out.println(a[i][j]); 
     } 

    } 

} 
+1

您可以發佈文件本身? – Pointy 2011-01-22 19:26:27

+0

我試過它的代碼它打印數組的值,但它會拋出一個異常,如果你到達文件的末尾! – palAlaa 2011-01-22 19:48:15

回答

8

while (input.next()!=null)

這將消耗從掃描儀輸入流的東西。相反,嘗試使用while (input.hasNextInt())

根據您希望代碼的可靠性,還應該在for循環中檢查是否有可讀的內容。

Scanner input = new Scanner (new File("src/array.txt")); 
// pre-read in the number of rows/columns 
int rows = 0; 
int columns = 0; 
while(input.hasNextLine()) 
{ 
    ++rows; 
    Scanner colReader = new Scanner(input.nextLine()); 
    while(colReader.hasNextInt()) 
    { 
     ++columns; 
    } 
} 
int[][] a = new int[rows][columns]; 

input.close(); 

// read in the data 
input = new Scanner(new File("src/array.txt")); 
for(int i = 0; i < rows; ++i) 
{ 
    for(int j = 0; j < columns; ++j) 
    { 
     if(input.hasNextInt()) 
     { 
      a[i][j] = input.nextInt(); 
     } 
    } 
} 

使用的ArrayList(無需預讀)另:

// read in the data 
ArrayList&ltArrayList&ltInteger>> a = new ArrayList&ltArrayList&ltInteger>>(); 
Scanner input = new Scanner(new File("src/array.txt")); 
while(input.hasNextLine()) 
{ 
    Scanner colReader = new Scanner(input.nextLine()); 
    ArrayList col = new ArrayList(); 
    while(colReader.hasNextInt()) 
    { 
     col.add(colReader.nextInt()); 
    } 
    a.add(col); 
} 
+0

這是不夠的,因爲`input.nextInt()`被稱爲`m x n`次。 – 2011-01-22 19:21:19

0

好這個問題可能是你已經有了一對嵌套的循環來讀取數字卡住那while循環。爲什麼你想要重讀數組值後,你讀過一次?並且請注意,如果在最後一個數字之後的文件中有任何東西,那麼您將在達到文件結束後用任何.nextInt()返回來填充數組!

編輯 —以及.nextInt()應該拋出一個異常,當輸入用完我想,這樣可能不是問題。

0

從簡單的開始...

變化:

for (int j=0;j<n;j++) 
    a[i][j]= input.nextInt(); 

到:

for (int j=0;j<n;j++) 
{ 
    int value; 

    value = input.nextInt(); 
    a[i][j] = value; 
    System.out.println("value[" + i + "][" + j + " = " + value); 
} 

,並確保該值在讀

而且,你不應該在沒有先調用(並檢查)hasNext(或nextInt/hasNextInt)的情況下調用next。

0

問題是,當你到達文件的末尾時,它會通過一個例外,即沒有usch元素存在。

public static void main(String[] args) { 
    // TODO Auto-generated method stub   
    try { 
     Scanner input = new Scanner(new File("array.txt")); 
     int m = 3; 
     int n = 5; 
     int[][] a = new int[m][n]; 
     while (input.hasNextLine()) { 
      for (int i = 0; i < m; i++) { 
       for (int j = 0; j < n; j++) { 
        try{// System.out.println("number is "); 
        a[i][j] = input.nextInt(); 
         System.out.println("number is "+ a[i][j]); 
        } 
        catch (java.util.NoSuchElementException e) { 
         // e.printStackTrace(); 
        } 
       } 
      }   //print the input matrix 
      System.out.println("The input sorted matrix is : "); 
      for (int i = 0; i < m; i++) { 
       for (int j = 0; j < n; j++) { 
        System.out.println(a[i][j]); 

       } 
      } 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

我知道在沒有處理異常但是它臨時工作的情況下捕獲。 請注意,我把文件放在源文件夾之外。

0

您可以嘗試使用番石榴,

public class MatrixFile { 
    private final int[][] matrix; 

    public MatrixFile(String filepath) { 
     // since we don't know how many rows there is going to be, we will 
     // create a list to hold dynamic arrays instead 
     List<int[]> dynamicMatrix = Lists.newArrayList(); 

     try { 
      // use Guava to read file from resources folder 
      String content = Resources.toString(
       Resources.getResource(filepath), 
       Charsets.UTF_8 
      ); 

      Arrays.stream(content.split("\n")) 
       .forEach(line -> { 
        dynamicMatrix.add(
         Arrays.stream(line.split(" ")) 
          .mapToInt(Integer::parseInt) 
          .toArray() 
        ); 
       }); 
     } catch (IOException e) { 
      // in case of error, always log error! 
      System.err.println("MatrixFile has trouble reading file"); 
      e.printStackTrace(); 
     } 

     matrix = dynamicMatrix.stream().toArray(int[][]::new); 
    }