2012-05-31 2 views
2

메신저 자바에서 프로그램을 테스트하려고 시도하고 내가 던져 야한다고 생각하지 않는 범위 밖의 배열 인덱스를 가져 오는 중입니다. 이 코드를 한번 보시고 무엇인가 놓치 셨는지 말씀해 주시겠습니까? 일식이 나에게 오류를 말하고하는 것은 내가 그것을배열 인덱스가 범위를 벗어나 예외가 발생 했습니까?

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가 어디에 있고 y가 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 

을가한다 반복 be mazeStore[y][x] 아니요 mazeStore[x][y]

+1

@Liam 맞다. 덧붙여서, 이것이 대부분의 장소에서 "x"와 "y"와 같은 변수를 피하는 이유입니다. 대신에 for (int row = 1; row <(2 * rows); row ++) 등으로 쓰여졌을 때 얼마나 더 명확했는지 생각해보십시오. – CPerkins

2

을 보여 코멘트를 추가 한 위치에 던져되고 당신 개봉 순서가 한다거나 할 수 있습니다. 개봉 된 배열을 사용하여 개봉 된 outter는 대부분 루프 행을 기반 있지만 당신은 초기화 된 컬럼의 크기로

관련 문제