1

我正在为我的机器人俱乐部使用 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);
    }
}

请帮忙!
谢谢

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

4

1 回答 1

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

于 2019-02-13T00:42:12.243 回答