2012-02-15 3 views
0

null 포인터 예외 문제가 있고 나는 몇 가지 문서를 읽은 그 오류가 여전히 무엇을 문제를 coundnt 알아 냈어.NullPointerException 오류를 수정하는 중 오류가 발생 했습니까?

오류는 방법으로 CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);

topIndex=0에서 발생합니다.

누구나 문제를 강조 할 수 있습니까?

여기 내 수업

public class Schedulingtest { 


public static void main (String[] args) throws IOException 
{ 

    Scanner fileScan; 

    fileScan=new Scanner(new File("data.txt")); 

    Schedule compatibility = new Schedule(); 


    while(fileScan.hasNext()) 
    {String url=fileScan.nextLine(); 
    compatibility.addActivity(url); 


    } 

} 


public class Schedule{ 


import java.util.Scanner; 
import java.util.Arrays; 

public class Schedule { 
Activity[] CompatibleActivity; 
int totalTime=0,topIndex=0; 
Scanner urlScan; 

public Schedule(){ 
Activity[] CompatibleActivity=new Activity[30]; 

} 


public int getTotalTime() 
{return totalTime; 
}  

public void addActivity(String entry){ 

    urlScan=new Scanner(entry); 
    urlScan.useDelimiter(" "); 

    String c=null; 
    int aNum = 0,bNum=0; 

    while(urlScan.hasNext()) 
    {String a=urlScan.next(); 
    String b=urlScan.next(); 
    c=urlScan.next(); 

    aNum=Integer.parseInt(a); 
    bNum=Integer.parseInt(b); 

      }  
    CompatibleActivity[topIndex]=new Activity(aNum,bNum,c); 
    topIndex++; 

    System.out.println("Activity added: start "+aNum+ " stop "+bNum+" "+c); 
}  

}

활동 Class 구성 NullPointerException이 그 줄에 확실히 경우

public class Activity { 

private int start,stop,duration; 
private String name; 

public Activity(int Start,int Stop,String Name) 
{ 
start=Start; 
stop=Stop; 
name=Name; 
duration=Stop-Start; 
}  

public String getName() 
{return name; 
}   

public int getStart() 
{return start; 
} 

public int getStop() 
{return stop; 
}   

public int getDuration() 
{return duration; 
}  

public boolean compatible(int Start1,int Stop1,int toMatchsideStart,int toMatchsideStop) 
{ 
    int Start=Start1; 
    int Stop=Stop1; 
    int toMatchStart=toMatchsideStart; 
    int toMatchStop=toMatchsideStop; 

if(toMatchStop<=Start) 
{return true; 
} 
if(toMatchsideStart>=Stop) 
{return true; 
} 
else 
{return false;}  
}   


public String toString() 
{return(name+"<"+start+","+stop+">"); }   
} 
+1

전체 스택 트레이스는 무엇인가 : 당신은 그것을 (예를 들어, 귀하의 생성자)에 충분한 요소가 실제 배열을 할당 할 필요가? – DaveJohnston

+1

어디에서'CompatibleActivity'를 선언합니까? 그리고이 배열을 어디에서 초기화합니까 (null이 아니기 위해)? – Thilo

+0

던져진 예외의 전체 스택 추적을 게시하십시오. –

답변

1

당신이 당신의 클래스에서 CompatibleActivity을 선언 한 대부분의 경우 같은 표현을해야합니다.

CompatibleActivity = new Activity[myBigNumber]; 
+0

코드의 또 다른 문제점은 'while'블록을 너무 일찍 종료했기 때문에 마지막 요소가 스캔 된 후에 만'CompatibleActivity'를 채우는 것입니다. 각 스캔 한 활동에 대한 것이 아닙니다. –

+0

사실 나는 클래스의 생성자에서 compatibileActivity를 추가하고 바깥 쪽 대부분의 Schedule 글로벌 클래스에 라인 코드를 추가하고 작동합니다. 이유를 이해하지 못하겠습니까? –

+0

코드의 문제점 중 하나는 형식이 잘못되었습니다. 그에 따라 모든 블록을 포맷하면 Java 언어에 익숙하지 않은 경우 이것이 작동하는 이유를 알게 될 것입니다.이 경우에는 주제에 대한 좋은 책을 권하고 싶습니다. [이 질문은] (http : // stackoverflow .com/questions/167179/java-tutorial) 참조). –

1

, 다음은 널 (null) 인 CompatibleActivity 발생할 수 있습니다. Array 객체가 선언 된 코드에서 코드를 찾아서 인스턴스화해야합니다.

Activity[] CompatibleActivity = new Activity[size]; 
1

어레이 중 하나에 액세스하기 전에 어레이를 초기화했는지 확인하십시오. 당신은 참조를 선언하고 기본적으로 null에 초기화

private Activity[] CompatibleActivity; 

CompatibilityActivity = new Activity[1]; // or any other positve number if size is bigger 
+0

내가 읽은 파일의 항목이 슬롯에 입력되도록 빈 슬롯 30 슬롯으로 초기화했습니다. –

+0

그런 다음 배열을 사용할 때 * 실제로 * 초기화되었는지 다시 확인하십시오. 문제를 일으키는 라인 바로 앞에'System.out.println (CompatibilityActivity.length)'를 추가하십시오. (NPE가 다음 줄로 이동합니다 * 새로운 행) –

0
Activity[] CompatibleActivity = new Activity[size]; 
// put some element in it like 
CompatibleActivity[0]=new CompatibleActivity(); 
관련 문제