当前位置: 代码迷 >> J2SE >> Exception in thread "main" java.lang.NullPointerException求大牛帮忙解决,30行小程序解决方案
  详细解决方案

Exception in thread "main" java.lang.NullPointerException求大牛帮忙解决,30行小程序解决方案

热度:5819   发布时间:2013-02-25 00:00:00.0
Exception in thread "main" java.lang.NullPointerException求大牛帮忙解决,30行小程序
public class smp11 {
public static void main(String args[])
{
ko lkl = new ko();
lkl.intiko();
}

}
class score
{
  int enGrade;
  public void setEn(int enGrade)
  {
this.enGrade=enGrade;  
  }
}
class ko
{
  score stug[] = new score[3];
  public void intiko()
  {
  stug[0].setEn(0);
  stug[1].setEn(1);
  stug[2].setEn(2);
  }
}
创建了两个类,不知道为什么会出现异常,明明已经new了啊

------解决方案--------------------------------------------------------
Java code
public class Smp11{    public static void main(String args[])    {        Ko lkl = new Ko();        lkl.intiko();    }    }class Score{    int enGrade;        public void setEn(int enGrade)    {        this.enGrade = enGrade;    }}class Ko{    Score stug[] = new Score[3];        public void intiko()    {        //需要先给数组中的元素赋值        stug[0] = new Score();        stug[1] = new Score();        stug[2] = new Score();                stug[0].setEn(0);        stug[1].setEn(1);        stug[2].setEn(2);    }}
------解决方案--------------------------------------------------------
具体做法
Java code
public class smp11 {public static void main(String args[]){ko lkl = new ko();lkl.intiko();}}class score{  int enGrade;  public void setEn(int enGrade)  {this.enGrade=enGrade;     }}class ko{  score stug[] = new score[3];  public void intiko()  {  stug[0]=new score();  stug[1]=new score();  stug[2]=new score();  stug[0].setEn(0);  stug[1].setEn(1);  stug[2].setEn(2);  }}
------解决方案--------------------------------------------------------
那是因为你没有实例化score.你定义了score为3的数组类型,却忽略了实例,必须报错,这样再实例一下就行了。
Java code
public class smp11 {    public static void main(String args[])    {    ko lkl = new ko();    lkl.intiko();    }    }    class score    {      int enGrade;      public void setEn(int enGrade)      {         this.enGrade=enGrade;         }    }    class ko    {      int len=3;      score[] stug = new score[len];       public void intiko()      {          for(int i=0;i<len;i++)          {              stug[i]=new score();          }          stug[0].setEn(0);          stug[1].setEn(1);          stug[2].setEn(2);      }    }
  相关解决方案