運行時出現 Exception in thread "main" java.lang.NullPointerException at Demo4.CycLink.createLink(Demo4.java:59) at Demo4.Demo4.main(Demo4.java:10) 不知道該如何處理 我有去查過全文,但因為實在是剛接觸,所以看不懂! 希望可以幫我解一下 以下是我的程式碼
package Demo4;
public class Demo4 { public static void main(String[] args) { CycLink cyclink=new CycLink(); cyclink.setLen(5); cyclink.createLink(); cyclink.show(); } }
class Child { int no; Child nextChild=null;
public Child(int no) { this.no=no; } }
class CycLink { Child firstChild=null; Child temp=null; int len=0;
public void setLen(int len) { this.len=len; }
public void createLink() { for(int i=1;i<=len;i++) { if (i==1) { Child ch=new Child(i); this.firstChild=ch; }
Exception in thread "main" java.lang.NullPointerException
at Demo4.CycLink.createLink(Demo4.java:59)
at Demo4.Demo4.main(Demo4.java:10)
不知道該如何處理
我有去查過全文,但因為實在是剛接觸,所以看不懂!
希望可以幫我解一下
以下是我的程式碼
package Demo4;
public class Demo4
{
public static void main(String[] args)
{
CycLink cyclink=new CycLink();
cyclink.setLen(5);
cyclink.createLink();
cyclink.show();
}
}
class Child
{
int no;
Child nextChild=null;
public Child(int no)
{
this.no=no;
}
}
class CycLink
{
Child firstChild=null;
Child temp=null;
int len=0;
public void setLen(int len)
{
this.len=len;
}
public void createLink()
{
for(int i=1;i<=len;i++)
{
if (i==1)
{
Child ch=new Child(i);
this.firstChild=ch;
}
else
{
if (i==len)
{
Child ch=new Child(i);
temp.nextChild=ch;
temp=ch;
temp.nextChild=this.firstChild;
}
else
{
Child ch=new Child(i);
temp.nextChild=ch;
temp=ch;
}
}
}
}
public void show()
{
Child temp=this.firstChild;
do
{
System.out.println(temp.no);
temp=temp.nextChild;
}while(temp!=this.firstChild);
}
}
{
Child ch=new Child(i);
this.firstChild=ch;
}