public class Test1 {
public static void main(String[] args) {
Cyclink cyclink = new Cyclink();
cyclink.setlen(5);
cyclink.setk(2);
cyclink.setm(2);
cyclink.creatlink();
cyclink.show();
cyclink.play();
}
}
class Child {
int no;
Child nextChild;
public Child(int no) {
this.no = no;
}
}
class Cyclink {
Child temp = null;
Child firstChild = null;
int len;
int k=0 ;
int m=0;
// private Child ;
public void setlen(int len) {
this.len = len;
}
public void setk(int k) {
this.k = k;
}
public void setm(int m) {
this.m = m;
}
public void play() {
Child temp=this.firstChild;
while(this.len!=1){
// 找到第K个shu
for (int i = 1; i < k; i++)
{
temp=temp.nextChild;
} //从第K个开始数m次
for(int j=1;j<m;j++)
{
temp=temp.nextChild;
}
Child temp2=temp;
while(temp2.nextChild!=temp)
{
temp2=temp2.nextChild;
}
temp2.nextChild=temp.nextChild;
temp=temp.nextChild;
this.len--;
}
System.out.println("抛出的"+temp.no);
}
public void creatlink() {
for (int i = 1; i <=len; i++) {
if (i == 1) {
Child ch = new Child(i);
this.firstChild = ch;
this.temp = ch;
}
if (i == len) {
Child ch = new Child(i);
temp.nextChild = ch;
temp = firstChild;
} else {
Child ch = new Child(i);
temp.nextChild = ch;
temp = ch;
}
}
}
public void show() {
Child temp;
temp=this.firstChild;
do {
System.out.println(temp.no);
temp=temp.nextChild;
} while (temp!=this.firstChild);
}
}
我写的代码
运行后的结果如下:
Exception in thread "main" java.lang.NullPointerException
at Cyclink.show(Test1.java:101)
at Test1.main(Test1.java:10)
1
1
2
3
4
5
我的问题是:
1.为什么编译没有出错 但是一运行就直接报出异常?
2.还有我的paly()函数好像没有运行啊这是什么原因?
求高手帮忙解答下 小弟不胜感激!!!
------最佳解决方案--------------------------------------------------------
逻辑有错误,所以出异常了,因为出了一场所以play()没有执行到。逻辑错误如下:
public void creatlink() {
for (int i = 1; i <=len; i++) {
if (i == 1) {
Child ch = new Child(i);
this.firstChild = ch;
this.temp = ch;
}
if (i == len) {
Child ch = new Child(i);