Search code examples
javanullpointerexceptionlego-mindstorms-ev3

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


I am working on setting up Java with lejos for my robotics club, and I was creating some basic drive methods, but when I organized it into the methods, it told me that I had a null pointer exception. Problem is that I don't know where it is or how to fix it.


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);
    }
}

Please help!
Thanks

p.s. (Each piece of code is supposed to be a seperate file.)


Solution

  • Please change:

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

    to:

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

    This will fix your NPE, and this is how a (not python!;) constructor looks like.