dimanche 14 avril 2019

NullPointerException when adding to an ArrayList from an if statement?

When I add things to my ArrayList, I get a NullPointerException, The other posts I have seen are usually to do with people not initialising the ArrayList, but I believe I have done that. I am fairly new to this so it is entirely possible the solution is something simple, but also possible that I've done it completely wrong.

In the main application:

    private MCP array;
    public void carInfo(standardSize standard) {

    System.out.println("Please enter number plate: ");
    input = new Scanner(System.in);
    String plate = input.nextLine();

    System.out.println("Please enter car make: ");
    input = new Scanner(System.in);
    String make = input.nextLine();

    System.out.println("Please enter the height of your vehicle: ");
    input = new Scanner(System.in);
    int height = input.nextInt();

    System.out.println("Please enter the length of your vehicle: ");
    input = new Scanner(System.in);
    int length = input.nextInt();

    if (length == 0 || height == 0) {
        System.out.println("cool one");
    }
    else if (length <= 2 && height >= 5) {
        standard.setPlate(plate);
        standard.setCarMake(make);
        standard.setHeight(height);
        standard.setLength(length);

        array.addStandard(standard);

        System.out.println(standard);
    }    `

it is called from a menu that calls "addStandard()"

private void addStandard() {
    standardSize standard = new standardSize();
    carInfo(standard);
}`

in the other class, I have the Array and the array.addStandard used before. ``` public ArrayList standards = new ArrayList<>();

public void addStandard(standardSize standard) {
standards.add(standard);
```

And lastly, I have my standardSize, which is used for the objects in the ArrayList ''' public class standardSize extends Car { public int height; public int length;

public standardSize(){
     super();
 }

 public standardSize(String plate, String carMake, int height, int 
 length){
    super(plate, carMake);
    this.height = height;
    this.length = length;
 }

public int getHeight() {
    return height;
}

public void setHeight(int height) {
    this.height = height;
}

public int getLength() {
    return length;
}

public void setLength(int length) {
    this.length = length;
}
}
'''

Again, I am sorry if this is an easy thing to fix, I'm just kind of stuck on it and the other posts I looked at didn't really help, also sorry if I have put too much code in my post.

I have seen the "what is a nullpointerexception post and I still can't make sense of it :/

Aucun commentaire:

Enregistrer un commentaire