Lejos EV3 "Null Pointer Exception",但我不确定如何修复它

Lejos EV3 "Null Pointer Exception", but I'm not sure how to fix it

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


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。 (每段代码都应该是一个单独的文件。)

请更改:

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!;)构造函数的样子。