有空指针异常的问题,我读了几篇文章回合那个错误,仍然可以找出问题所在。
错误发生在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 );
}
}
活动类
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+">"); }
}
答案 0 :(得分:1)
如果NullPointerException肯定在该行上,那么它只能由CompatibleActivity为null引起。您需要在代码中找到声明该Array对象的位置,并确保它也被实例化,例如。
Activity[] CompatibleActivity = new Activity[size];
答案 1 :(得分:1)
在访问其中一个单元格之前,请检查是否已初始化阵列。你需要一个像
这样的表达式CompatibilityActivity = new Activity[1]; // or any other positve number if size is bigger
答案 2 :(得分:1)
您很可能在课堂上宣布CompatibleActivity
为
private Activity[] CompatibleActivity;
默认声明引用并将其初始化为null
。你需要为它分配一个包含足够元素的真实数组(例如在你的构造函数中):
CompatibleActivity = new Activity[myBigNumber];
答案 3 :(得分:0)
Activity[] CompatibleActivity = new Activity[size];
// put some element in it like
CompatibleActivity[0]=new CompatibleActivity();