2014-10-20 4 views
0

2darray of objects (셀)의 위치가 비어 있는지 컨설팅을하는 동안 왜 NPE를 얻는 지 모르겠습니다. 나는 if ((matrix[i][j]) == null)에 의하여 이것을 검사하고 나는 if ((matrix[i][j]) != null)를 시도하고 그러나 메신저 NPE를 몇번이고 얻는. 나는왜이 경우에 NullPointerException이 발생합니까?

public class 2darrayofcells { 

//rows and columns are final by requirement 
private final int rows; 
private final int colums; 
private Cell[][] matrix; 
//the array needs an initial object 
private Cell initialCell; 

//Position class consist on 2 integers (x,y) 

public 2darrayofcell(Position pos){ 
    //the arg pos is used to create the initial cell in the specified position of the array 
    rows = 10; 
    columns = 10; 
    matrix = new Cell[rows][columns]; 
    initialCell = new Cell(); 
    matrix[pos.getX()][pos.getY()] = initialCell; 

} 

. . . 

//Here i put a cell in a position of the array but before putting it 
//i need to know if it's empty. It will return true if the cell is added to 
//that position 
public boolean putCell(Cell cell, Position pos){ 

    //Null Pointer Exception 
    if (matrix[pos.getX()][pos.getY()] == null) { 

     //Do stuff 
     return true; 
    } 
    return false; 
} 

} 

메인 클래스 사용자의 통화에서

매트릭스는 초기화를 가지고
public static void main(String[] args) { 


    Position pos = new Position(5,5); 
    2darrayofcells test = new 2darrayofcells(pos); 
    //test only has an object in 5,5 
    //The position for the cell i want to insert (3,3) is empty 
    Position cellPos = new Position(3,3); 
    Cell testCell = new Cell(); 
    test.putCell(testCell, cellpos); 


} 

...

+0

코드를 컴파일 할 수 있습니까? Cell/Position 클래스의 정의는 무엇입니까? – SMA

+0

자바가 클래스 이름을 2darrayofcells 클래스 이름과 충돌하는 숫자 문자로 시작하도록하고 클래스의 생성자 (public 2darrayofcell (Position pos))가 잘못된 서명을 가지고 있다고 생각하지 않아서 코드를 컴파일 할 수 있습니까? 아마도 ' 이름 끝. – Himanshu

+0

@almasshaikh 코드가 컴파일되고, funcionalities를 시도 할 때 문제가 발생했습니다. 셀은 2 정수를 포함합니다. – Jan

답변

0

이 줄에 NPE에 대한 세 가지 가능한 설명이 있습니다.

설명 # 2 : posnull입니다.

설명 # 3 : matrix[pos.getX()]null입니다.


어떤 설명이 올바른지 알아낼 수 없습니다. 기본적으로 코드 스 니펫은 일관성이 없습니다 (즉, 컴파일되지 않음). 불일치로 인해 실제 코드에서 어떤 일이 발생하는지 판단하기가 불가능합니다.

컴파일 오류를 무시하더라도 코드의 다른 부분은 설명이 정확하지 않다는 것을 암시하는 것처럼 보입니다. 그러나 은 사실 일 수 없습니다.. 위의 라인이 NPE를 던지면 위의 세 가지 설명 이외에 다른 가능한 설명이 없습니다. 없음.

+0

이상 하네. 행렬에는 기본적으로 생성 된 모든 요소가 있습니다 (null). 매트릭스가 존재합니다 ... – Jan

+0

나는 당신을 도울 수 없습니다. 귀하의 질문에있는 코드는 분명히 실제 코드가 아닙니다. SSCCE를 게시하지 않으면 더 이상 도움을 드릴 수 없습니다. –

+0

어쨌든, 고마워. 나는 내 코드를 다시 읽게 될 것이다. 아마 그 세 가지 설명 중 하나와 관련된 어떤 이슈도 보지 못했을 것이다. – Jan

0

에 ... 난 그 NPE없이 확인 방법을 알고 싶어요 putCell(), cellPos를 두 번째 인수로 전달하지 않으시겠습니까?

if (matrix[pos.getX()][pos.getY()] == null) { 

설명 # 1 : matrixnull입니다

+0

예, 글을 잊어 버립니다. 지금 편집 중입니다. – Jan

0

내가 셀이 어떻게 보이는지 모르겠지만, 당신은 아마 디폴트 값에 null 세포에 게터를 사용하려고 :

if (matrix[pos.getX()][pos.getY()] == null) 
pos.getX() throws NullPointerException 

시도 :

if (matrix[0][0] == null) { 

가 작동합니까?

+0

아니요 ...일을하기 위해 예외를 던질 필요가 있더라도 나는 모른다. – Jan

관련 문제