2012-04-22 17 views
-2

목표는 스택을 사용하여 미로를 통과하는 것이지만 너무 멀어 질 수는 없습니다.2D 배열을 사용할 때 NullPointerException이 발생했습니다.

저는 Room 개의 2D 배열을 가지고 있으며 항상 1,1 위치부터 시작합니다. 나는 모든 것이 올바르게 설정되었다고 믿는다. 그러나 배열에 저장된 데이터에 액세스하려고 할 때마다 계속 NullPointerException이 계속 표시됩니다.

올바른 방향으로 나에게 도움이 될만한 도움을 주시면 감사하겠습니다.

import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.PrintWriter; 
import java.util.*; 

import javax.swing.JOptionPane; 


public class Maze { 
String inFile,    // Name of file to be used as input 
     outFile,    // Name of file to output completed maze to 
     line;    // Current line being read by scanner 
    char [][] mazeContent; 
    Room [][] rooms;// Holds the values that create maze 
    Room [] theStack; 
    Room current = new Room(); 
    ArrayList<Room> al; 
    int rows, columns; 
    int tos = 0; 
    char [][] mazeC; 

    public static void main(String []args) throws Exception { 
    Maze m = new Maze(); 
    } 

    public Maze() throws FileNotFoundException { 
     // Prompts user for the name of the file they wish to use as the input file. 
     inFile = JOptionPane.showInputDialog(null, "Please enter the name of the file you wish to read, including " + 
     "the file path:"); 
     //if(inFile.equals("")) inFile = "C:\Java\JavaFiles\maze1.txt; 
     // Prompts user to enter the name they wish to save the file under. 
     outFile = JOptionPane.showInputDialog(null, "Please enter the filename you wish to save the data to:"); 
     // Creates a scanner object to read in the input file. 
     Scanner readFile = new Scanner(new FileReader(inFile)); 
     PrintWriter output = new PrintWriter(outFile); 
     rows = readFile.nextInt(); 
     columns = readFile.nextInt(); 
     readFile.nextLine(); 
     theStack = new Room[1000]; 
     mazeContent = new char [rows][columns]; 
     rooms = new Room [rows][columns]; 
     theStack = new Room[1000]; 

     for(int i = 0; i < rows; i++) { 
     line = readFile.nextLine(); 
     for(int j = 0; j< line.length(); j++) { 
     mazeContent[i][j] = line.charAt(j);   
     } 
     } 

     createRooms(); 
     findPath(); 
    } 


    private void findPath() { 
    Room start = rooms[1][1]; 
    push(start); 
     while(!isEmpty()) { 
    current = pop(); 
    //System.out.println("The value is " + current.getValue()); 
    if(current.getValue() == '$') { 
     System.out.println("Success"); 
    } 
    else if(current.getBlocked() != true && current.getVisited() != true) { 
       current.setVisited(true); 
       push(current.getRight()); 
       push(current.getLeft()); 
       push(current.getUp()); 
       push(current.getDown()); 
    } 
    } 
    } 

    public void createRooms() { 
    for(int i = 1; i < rows - 1; i++) { 
    for(int j = 1; j < columns -1; j++) { 
       Room r = new Room(); 
       r.setCord(i,j); 
       r.setValue(mazeContent[i][j]); 
       r.setUp(rooms, i-1, j); 
       r.setDown(rooms, i+1, j); 
       r.setRight(rooms, i, j+1); 
       r.setLeft(rooms, i, j-1); 
       if(mazeContent[i][j] == '*') 
        r.setBlocked(true); 
       else 
        r.setBlocked(false); 
       rooms[i][j] = r; 
    } 
    } 
    } 

    private Room pop() { 
    return theStack[--tos]; 
    } 

    private boolean isEmpty() { 
    // TODO Auto-generated method stub 
    return tos == 0; 
    } 

    private void push(Room item) { 
    if (isFull()) { 
    System.out.println("The stack is full!"); 

    } 
    else 
     theStack[tos++] = item; 
    } 

    private boolean isFull() { 

    return tos == theStack.length-1; 
    } 

} 
+3

스택 추적을 게시하십시오. – Lucas

+0

예. 어떤 라인에서 NPE를 얻을 수 있습니까? –

+1

위의 코드를 해독하려고하는 사람은 거의 없습니다. 하지만 "null 포인터"예외가 발생하는 이유는 설정하지 않았거나 명시 적으로 null로 설정했기 때문에 null 인 객체 참조 (포인터)를 참조하기 때문입니다. 약간의 디버깅은 객체 참조가 null인지 알려주고 거기에서 거꾸로 작업 할 수 있습니다. 여기 몇 사람이 당신을 위해 당신의 일을 할 것입니다. –

답변

1

하여 NullPointerException이의 가장 가능성있는 근본 원인은 당신이하지 (완전) 뭔가를 초기화 한 것입니다 :

import java.awt.Point; 


public class Room { 
private Room up; 
private Room down; 
private Room left; 
private Room right; 
private char value; 
private boolean blocked; 
private boolean visited = false; 
private Point p; 

public void setCord(int row, int column) { 
p = new Point(row, column); 
} 

public void setUp(Room [][] r, int row, int column) { 
up = r[row][column];  
} 


public void setDown(Room[][] r, int row, int column) { 
down = r[row][column]; 

} 

public void setRight(Room[][] r, int row, int column) { 

right = r[row][column]; 
} 

public void setLeft(Room[][] r, int row, int column) { 

left = r[row][column]; 
} 

public void setValue(char c) { 

value = c; 
} 

public void setVisited(boolean b) { 
visited = b; 
} 
public void setBlocked(boolean b) { 
blocked = b; 
} 

public Point getCord() { 
return p; 
} 

public Room getUp() { 
return up; 
} 


public Room getDown() { 
return down; 
} 

public Room getRight() { 

return right; 
} 

public Room getLeft() { 

return left; 
} 

public char getValue() { 

return value; 
} 
public boolean getVisited() { 
return visited; 
} 

public boolean getBlocked() { 
return blocked; 
} 


} 

가 여기 내 미로 클래스입니다 :

여기 내 방 클래스입니다. 아마도 당신의 물건 중 하나의 필드. 아마도 배열의 요소 일 것입니다. 이 초기화되지 않은 필드 또는 배열 요소를 사용하려고하면 실제로 null 참조에서 작업을 수행하려고하는데 예외가 발생합니다. 예외가

if(current.getValue() == '$') 

의해 발생되는 경우


는 그 currentnull는 것을 의미한다. 즉, 스택에서 null을 "팝"했습니다. 첫눈에, 당신의 스택 연산의 구현은 괜찮아 보입니다. 그래서 제 생각 엔 null을 밀어 넣은 것 같습니다.

내 제안은 null을 푸시하려고 시도하면 예외를 throw하는 push 메서드에 테스트를 추가하는 것입니다. (또는 디버거를 사용하여이를 추적 해보십시오.) 그런 다음 뒤로 작업하여 null의 출처를 확인하십시오.

+0

오 이런. 이것이 바로 문제입니다. 감사. – user994602

+0

@ user994602 당신을 위해 작동하는 경우 대답을 수락하십시오. – Nikhar

관련 문제