您好StackOverflow用戶。這與Java而不是機器人本身有關。我試圖做的是將運動方法中的傳感器分開,以使代碼易於閱讀,但是我遇到了一個問題。Java Lejos拋出nullpointerException
Sensor.java
package sensors;
import lejos.hardware.sensor.EV3ColorSensor;
import lejos.hardware.sensor.EV3GyroSensor;
import lejos.hardware.sensor.EV3TouchSensor;
import lejos.hardware.sensor.EV3UltrasonicSensor;
public class Sensors {
EV3TouchSensor touchSensor;
EV3ColorSensor colorSensor;
EV3GyroSensor gyroSensor;
EV3UltrasonicSensor ultrasonicSensor;
public Sensors(EV3TouchSensor t, EV3ColorSensor c, EV3GyroSensor g, EV3UltrasonicSensor u) {
touchSensor = t;
colorSensor = c;
gyroSensor = g;
ultrasonicSensor = u;
}
public int getColorSample(){
int sample = colorSensor.getColorID();
return sample;
}
}
Movement.java
public class Movement {
RegulatedMotor left;
RegulatedMotor right;
EV3TouchSensor touchSensor;
EV3ColorSensor colorSensor;
EV3GyroSensor gyroSensor;
EV3UltrasonicSensor ultrasonicSensor;
public Movement(RegulatedMotor l, RegulatedMotor r, EV3TouchSensor t, EV3ColorSensor c, EV3GyroSensor g,
EV3UltrasonicSensor u) {
left = l;
right = r;
touchSensor = t;
colorSensor = c;
gyroSensor = g;
ultrasonicSensor = u;
}
//initialize sensors
Sensors sensors = new Sensors(touchSensor, colorSensor, gyroSensor, ultrasonicSensor);
public void moveForward() {
// get the color sample of the ground
//int sample = colorSensor.getColorID();
int sample = sensors.getColorSample();
// while machine is on the ground color
while (sample != 7) {
// get new sample
//sample = colorSensor.getColorID();
sample = sensors.getColorSample();
// move forward
syncForward();
}
// if on black, stop motors.
syncStop();
}
不要看其他的方法,因爲這些工作流利,但錯誤出現在第30行,它會嘗試從傳感器類中獲取樣本。 我不知道,我已經給出了註釋掉的行,以及流利的工作。 錯誤來自訪問傳感器類,我可以'想出一個解決方案。
我會在你的債務!
您能否在您的代碼段中標記#30行? – AlexR
你可以發佈你的stacktrace嗎? – stuXnet
除了初始化之外,還有其他的傳感器分配嗎? – DBug