My program currently takes in data on cars, like weight, engine size and color, it then creates an object car and sets those values inside the object.
The object is then added to an Arraylist of car which is in a separate class. When trying to display the properties of say the first car by doing Arraylist.get(0).color it says my Arraylist is null.
I've looked into it and it seems like I'm re-initializing the Arraylist but I don't see how.
This is the code that sets the object car as well as the code for the car object and the constructor for the class:
public class AddCar {
public static MainMenu menu = new MainMenu();
public Car car;
CarList carList;
//constructor for the AddCar
public AddCar(){carList = new CarList();}
public class Car{
int weight;
String engine;
String color;
public Car(){}
public Car(weight, engine, color)
{
wt = weight;
eng = engine;
col = color;
}
}
public void addCar(){
int weight = 3000;
String engine = 6L
String color = blue;
car = new Car(weight, engine, color);
carList.addCar(car);
menu.user_input();
}
public void displayCar()
{
custList.dispCar();
}
The method addCar is from a separate class file which just adds the car to the end of an Arraylist, here is that code:
public class CarList {
List<Car> car_list;
public CarList()
{
car_list = new ArrayList<Car>(10);
}
//method to add car to arraylist
public void addCar(Car car)
{
car_list.add(car);
//this print statement works fine
System.out.println(car_list.get(0).color);
}
//method to display color property of first car
public void dispCar()
{
//this print statement comes back with null pointer exception
System.out.println(car_list.get(0).color);
}
This issue occurs when you use the method dispCar from the above class, it throws a null pointer exception.
And then this is the MainMenu where you choose the option for what to do:
public class MainMenu {
private static Scanner keyboard1 = new Scanner(System.in);
private AddCar add;
public MainMenu()
{
add = new AddCar();
}
public void user_input()
{
System.out.println("Pick an Option:");
System.out.println("1. Add a car");
System.out.println("2. Remove a car");
System.out.println("Please enter the option #:");
int option = keyboard1.nextInt();
switch (option){
case 1: add.addCar();
case 2: add.displayCar();
}
}
}
displayCarof the classAddCar, please add it to your question.AddCar(your case1) beforedisplayCar?CarList.addCarmethod isCustomerwhen it should beCar