Lejos EV3“空指针异常”,但我不确定如何解决

时间:2019-02-12 23:46:42

标签: java nullpointerexception ev3

我正在为我的机器人俱乐部使用lejos设置Java,并且正在创建一些基本的驱动器方法,但是当我将它们组织到这些方法中时,它告诉我我有一个空指针异常。问题是我不知道它在哪里或如何修复。


import lejos.hardware.motor.*;
import lejos.hardware.port.*;

public class HardwareMappings {

    EV3LargeRegulatedMotor leftDrive = null;
    EV3LargeRegulatedMotor rightDrive = null;


    public void init(HardwareMappings ahwMap) {
        leftDrive = new EV3LargeRegulatedMotor(MotorPort.B);
        rightDrive = new EV3LargeRegulatedMotor(MotorPort.C);

    }

}

public class DrivetrainMethods {

    HardwareMappings robot = new HardwareMappings();

    public void TimedDrive(int direction, int power, double time) throws InterruptedException {
        robot.leftDrive.setSpeed((power * 60) - direction);
        robot.rightDrive.setSpeed((power * 60) + direction);
        Thread.sleep((long) (time * 60));
        robot.leftDrive.stop(true);
        robot.rightDrive.stop(true);
    }

    public void TankDrive (int leftPower, int rightPower, double time) throws InterruptedException {
        robot.leftDrive.setSpeed(leftPower);
        robot.rightDrive.setSpeed(rightPower);
        Thread.sleep((long) (time * 60));
        robot.leftDrive.stop(true);
        robot.rightDrive.stop(true);
    }
}

public class Test {

    public static void main (String[] args) throws InterruptedException{

        DrivetrainMethods drivetrain = new DrivetrainMethods();

        drivetrain.TimedDrive(0, 50, 1);
        drivetrain.TankDrive(-50, -50, 1);
    }
}

请帮助!
谢谢

p.s。 (每段代码都应该是一个单独的文件。)

1 个答案:

答案 0 :(得分:0)

请更改:

public void init(HardwareMappings ahwMap) {//this code will be invoked on:
    // someHardwareMappings.init(otherHardwareMappings);
    leftDrive = new EV3LargeRegulatedMotor(MotorPort.B);
    rightDrive = new EV3LargeRegulatedMotor(MotorPort.C);
}

收件人:

public HardwareMappings() { // this code will be invoked on:
    // new HardwareMappings();)
    leftDrive = new EV3LargeRegulatedMotor(MotorPort.B);
    rightDrive = new EV3LargeRegulatedMotor(MotorPort.C);
}

这将修复您的NPE,这就是(不是python !;)构造函数的样子。