我已经创建了下面的静态类,因此任何类都可以访问我的 lejos 机器人的任何传感器方法,而无需我为每个类创建一个实例。
但是,每当我调用诸如 StandardRobot.motorA.setPower(100)
之类的方法时,我的机器人就会崩溃。当我使用完全相同的类并创建它的本地实例时,效果很好。为什么是这样?这两次我的代码都编译得很好,但在运行时失败了。
import lejos.nxt.*;
public class StandardRobot {
public static ColorSensor colourSensor;
public static TouchSensor touchSensor;
public static UltrasonicSensor ultrasonicSensor;
public static NXTMotor motorA, motorB;
public StandardRobot() {
// instantiate sensors
ultrasonicSensor = new UltrasonicSensor(SensorPort.S1);
colourSensor = new ColorSensor(SensorPort.S2);
touchSensor = new TouchSensor(SensorPort.S4);
//instantiate motors
motorA = new NXTMotor(MotorPort.A);
motorB = new NXTMotor(MotorPort.B);
}
}
最佳答案
您正在尝试创建一个实用程序类,但变量初始化是在构造函数中进行的。
仅当实例被...构造时才会调用构造函数(通过new
)。
您需要在静态初始化 block 中或在声明静态属性时静态初始化静态属性。
// Initialize static properties as they're declared.
public static ColorSensor colourSensor = new ColorSensor(SensorPort.S2);
// Or initialize in a static initialization block to do them all at once.
public static TouchSensor touchSensor;
// ... and the others.
static {
touchSensor = new TouchSensor(SensorPort.S4);
// ... and the others.
}
关于java - 为什么静态类会使我的机器人崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7885272/