以下代码中的getDistance()
函数无法正常工作。不同的实例未正确传递距离值。正确的值如下:d1 = 0
,d2 = 1
,d3 = 2
。
我的代码有什么问题?
package javaapplication28;
public class JavaApplication28 {
public interface State {
public double getDistance();
public State getParent();
}
public static void main(String[] args) {
abstract class AbstractState implements
State {
private State parent = null;
protected double distance = 0;
public AbstractState(State parent) {
this.parent = parent;
this.distance = parent.getDistance() + 1;
}
}
class ThisState extends AbstractState {
State parent;
public ThisState(State parent) {
super(parent);
}
public State getParent() {
return parent;
}
public double getDistance() {
return distance;
}
}
ThisState TS1 = new ThisState(null);
ThisState TS2 = new ThisState(TS1);
ThisState TS3 = new ThisState(TS2);
int d1 = TS1.getDistance();
int d2 = TS2.getDistance();
int d3 = TS3.getDistance();
}
}
感谢您回答我的问题!
答案 0 :(得分:2)
当你运行时:
ThisState TS1 = new ThisState(null);
如果将parent
设置为null
:
public AbstractState(State parent) {
this.parent = parent;
this.distance = parent.getDistance() + 1;
}
将导致构造函数的第二行中出现空指针异常。
您需要做的是仅在父级不为空时将距离设置为parent.getDistance() + 1
答案 1 :(得分:1)
问题在于:
if (parent != null) { // Hello !?
this.distance = parent.getDistance() + 1;
}
完整代码:
public class Application4995 {
public interface State {
public double getDistance();
public State getParent();
}
public static void main(String[] args) {
abstract class AbstractState implements State {
private State parent = null;
protected double distance = 0;
public AbstractState(State parent) {
this.parent = parent;
if (parent != null) { // Hello !?
this.distance = parent.getDistance() + 1;
}
}
}
class ThisState extends AbstractState {
State parent;
public ThisState(State parent) {
super(parent);
}
public State getParent() {
return parent;
}
public double getDistance() {
return distance;
}
}
ThisState TS1 = new ThisState(null);
ThisState TS2 = new ThisState(TS1);
ThisState TS3 = new ThisState(TS2);
double d1 = TS1.getDistance(); // or int d1 = (int) TS1.getDistance();
double d2 = TS2.getDistance(); // or int d2 = (int) TS2.getDistance();
double d3 = TS3.getDistance(); // or int d3 = (int) TS3.getDistance();
}
}