2012-01-28 31 views
0

這是我用來從文件加載保存的遊戲數據的方法。由於這個原因,我在某個時候收到了一個名爲error15的東西。 Google上唯一發生的事情就是與http有關,但這不可能,因爲我沒有這樣做。當對象將字符串打印到控制檯時,它會完成保存的第一行數據,但不會繼續讀取其他數據。我有一種預感,它可能與我使用in.nextLine();(有沒有其他我應該用來代替?)如果任何人都可以告訴我我做錯了什麼,我會永遠愛你。我的負載數據方法有什麼錯誤?

/** 
* Returns a 2-dimensional 15*15 array of saved world data from a file named by x and y coordinates 
*/ 
public String[][] readChunkTerrain(int x, int y) 
{ 
    String[][] data = new String[15][15]; //the array we will use to store the variables 
    try { 
     //initiate the scanner that will give us information about the file 
     File chunk = new File("World/" + x + "." + y + ".txt"); 
     Scanner in = new Scanner(
       new BufferedReader(
        new FileReader(chunk))); 

     //go through the text file and save the strings for later 
     for (int i=0; i<15; i++){ 
      for (int j=0; j<=15; j++){ 
       String next = in.next(); 
       data[i][j] = next; 

       System.out.println(i + j + next); //temporary so I can see the output in console 
       System.out.println(); 
      } 
      in.nextLine(); 
     } 

     in.close(); //close the scanner 
    } 
    //standard exception junk 
    catch (Exception e) 
    {System.err.println("Error" + e.getMessage());} 

    return data; //send the array back to whoever requested it 
} 

回答

0

與你得到的15(你應該有BTW張貼,並會導致立即回答這個問題)的誤差可能是一個ArrayIndexOutOfBoundsException因爲您嘗試訪問data[i][15]在循環,它不存在。

for (int i=0; i<15; i++){ 
     for (int j=0; j<=15; j++){ 

j循環應該調整你的data變量作爲new String[15][15]初始化匹配i循環。所以它轉換成以下,所有工作將注

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

<代替<=

+0

非常感謝;工作!我其實確實發佈了錯誤。它只是說「錯誤15」。 – ChemicalRocketeer 2012-01-28 22:04:36

+0

多虧了你的錯誤處理。 'System.err.println(「Error」+ e.getMessage())'不會輸出太多信息。至少調用'e.printStackTrace()',以便知道錯誤發生的位置以及錯誤的類型 – Robin 2012-01-28 22:32:32