2012-05-31 21 views
2

即時試圖在java中測試一個程序,我得到一個數組索引越界異常,我不認爲應該拋出。看看這段代碼,並告訴我,如果我錯過了什麼?日食告訴我的錯誤被拋出在我添加了一個評論,以顯示它數組索引超出範圍異常,是否意味着發生?

class maze{ 

private int cols; // number of columns in maze 
private int rows; // number of rows in maze 
private String name; 
private weightedGraph<Integer> graph; 
private dijkstra solution; 
public char[][] mazeStore; 

public maze(String filename){ 

    try{ 

     FileReader r = new FileReader(filename); 
     Scanner s = new Scanner(r); 
     this.rows = s.nextInt(); 
     this.cols = s.nextInt(); 
     this.name = filename; 


     this.mazeStore = new char[(2*rows)+1][(2*cols)+1]; 
     String line = s.nextLine(); 
     for(int k = 0; k < ((2*rows)+1); k++){ 

      char[] temp = line.toCharArray(); 

      for(int i = 0; i < temp.length; i++){ 
       mazeStore[k][i] = temp[i]; 
       line = s.nextLine(); 
      } 
     } 



     graph = new weightedGraph<Integer>(rows*cols); 


     for(int y = 1; y < 2*rows; y++){ 
      for(int x = 1; x < 2*cols; x++){ 
       if((x % 2 == 1) && (y % 2 == 0)){ 
        if(mazeStore[x][y] != '-'){ // <<<<<<<<<<<<<<THIS IS WHERE THE ERROR IS THROWN 
         int label = (x - 1) + (x/2); 
         graph.addEdge(label, label+cols, 1); 
         graph.addEdge(label+cols, label, 1); 
        } 
       } 

       if((x % 2 == 0) && (y % 2 == 1)){ 
        if(mazeStore[x][y] != '|'){ 
         int label = ((x - 1) + (x/2)) + (y/2); 
         graph.addEdge(label, label+1, 1); 
         graph.addEdge(label+1, label, 1); 
        } 
       } 
      } 
     } 



     this.solution = new dijkstra(graph, 0); 


    } 
    catch(FileNotFoundException e){ 
     System.err.println("FileNotFoundException: " + e.getMessage()); 
    } 
+4

那麼,那個時候'x'和'y'的值是什麼,以及這個數組的長度是多少涉及? –

+2

1)爲了更快獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)複製/粘貼錯誤消息。 –

+1

我認爲x應該是y的地方,反之亦然 – Bundy

回答

5

你初始化數組

new char[(2*rows)+1][(2*cols)+1] 

但迭代它

for(int y = 1; y < 2*rows; y++){//y row iterator 
    for(int x = 1; x < 2*cols; x++){//x col iterator 

所以應該是 mazeStore[y][x]不是mazeStore[x][y]

+1

@Liam是的,正好。順便說一句,這就是爲什麼大多數地方要避免使用「x」和「y」等變量的原因。想一想,如果把它寫成'for(int row = 1; row <(2 * rows); row ++)',等等會有多清晰。 – CPerkins

2

位置你的youre varaibles失靈。您選擇outter最環路是基於行,但你使用的是數組中你初始化爲列的大小