2017-04-23 85 views
0

我想讀取一個txt文件到2d字符數組。我的問題是我試圖做的方式產生一個錯誤。你將如何用txt文件填充這個數組?如何讀取文件到2d字符數組

public char[][] readFile(String filename) { 

    try { 

     Scanner scan= new Scanner(new File(filename)); 



     int x= scan.nextInt(); 
     int y = scan.nextInt(); 
     char [][] maze= new char [x][y]; 
     for(int i=0;i<maze.length; i++){ 
      for(int j=0; j< maze[i].length; j++){ 
       maze[i][j]= scan.next().toCharArray(); 

      } 
     } 


     return maze; 

    } catch (FileNotFoundException e) { 
     return null; 

    } 

} 
+0

它似乎是一個編譯錯誤導致行maze [i] [j] = scan.next.toCharArray(); –

+0

您正在嘗試在字符中存儲char數組 –

+0

現在它說線程「main」中的異常java.util.NoSuchElementException –

回答

0
maze[i]= scan.next().toCharArray(); 

只是這樣做。但是,如果toCharArray()返回的數組超出列(y)大小聲明的大小,它可能會在運行時產生異常。

+0

這是構建數組,除了測試代碼是說「readFile不正確構建數組。」。所以我不知道現在發生了什麼 –

+0

確保.txt文件中的字符被一個空格分開。 –

+0

是這樣的:1 1 1 1 –

相關問題