2
\$\begingroup\$

I have recently started coding in Java and I had to do this assignment in college.

Develop a menu driven application called TestCarPartc that allows the user to add, remove and list Car objects. For this use an ArrayList of Car. What are the advantages of using an ArrayList over an array? Place the answer in a comment at the end of your code.

I am trying to wrap my head around the concept of OOP and I am not quite sure when should I make something a new class or if I should implement something as interface or make some classes inherit from the other.

How does it look like in a real programming job? Would my code be considered "well written" for its purposes? What are the things I should look out for?

Console Menu:

package CarPartsB;

import java.util.InputMismatchException;
import java.util.Scanner;

public class CarPartsMenu {

Scanner console = new Scanner(System.in);
private CarsArray carsList = new CarsArray();
private boolean loopVariable = true;

public void showMenu() {

    while (loopVariable) {
        try {
            System.out.println("1: Add car.\n2: Remove car.\n3: List cars.\n4: Exiting");
            int userInput = console.nextInt();
            switch (userInput) {
                case 1:
                    addCar();
                    break;
                case 2:
                    removeCar();
                    break;
                case 3:
                    listCars();
                    break;
                case 4:
                    loopVariable = false;
                    break;
            }
        } catch (InputMismatchException e) {
            console.nextLine();
            System.out.println("\n" + e + " \nhas happened, choose value from 1 o 4.\n Click enter to continue...");
            console.nextLine();
        }
    }
}

private void addCar() {
    String make, model;
    int year;
    double price;
    try {
        System.out.println("What's price of your car? ");
        price = console.nextDouble();
        validateInput(price);
        System.out.println("What year was your car made?");
        year = console.nextInt();
        validateInputYear(year);
        System.out.println("What's the make of your car?");
        make = console.next();
        System.out.println("What's the model of your car?");
        model = console.next();
        Car car = new Car(price, year, make, model);
        carsList.addCar(car);
    } catch (InputMismatchException e) {
        console.nextLine();
        System.out.println("\n" + e + "\nhas happened, make sure to input correct values.\n Click enter to continue...");
        console.nextLine();
    }
}

private void removeCar() {
    if (carsList.isEmpty()) {
        console.nextLine();
        System.out.println("There are no cars in the list");
        console.nextLine();
    } else {
        try {
            System.out.println("Type id of the car you want to remove: ");
            int userInputID = console.nextInt();
            carsList.removeCar(userInputID);
            System.out.println("Car with ID: " + userInputID + " has been removed.\n");
            console.nextLine();
        } catch (IndexOutOfBoundsException e) {
            console.nextLine();
            System.out.println("\n" + e + "\nhas happened, you have to pick ID that EXISTS.\n Click enter to continue...");
            console.nextLine();
        } catch (InputMismatchException e) {
            console.nextLine();
            System.out.println("\n" + e + "\nhas happened, input an integer.\n Click enter to continue...");
            console.nextLine();
        }
    }
}

private void listCars() {
    console.nextLine();
    System.out.println("List of cars: ");
    carsList.printCars();
    System.out.println("\nPress anything to continue...");
    console.nextLine();
}

private void validateInputYear(int number) {
    if (number < 1900 || number > 2018) {
        throw new InputMismatchException("\nYou can't add car that was made earlier than 1900\n or after 2018");
    }
}

private void validateInput(double number) {
    if (number <= 0) {
        throw new InputMismatchException("\nPrice can't be negative or zero.");
    }
}

}

Array Class:

package CarPartsB;
import java.util.ArrayList;

public class CarsArray {

    private ArrayList<Car> carsArray;

    public CarsArray() {
        this.carsArray = new ArrayList();
    }

    public ArrayList<Car> getCars() {
        return this.carsArray;
    }

    public int size() {
        return this.carsArray.size();
    }

    public void addCar(Car element) {
        this.carsArray.add(element);
    }

    public void removeCar(int carId) {
        Car carToRemove = null;
        for (Car c : carsArray) {
            if (c.getCarID() == carId) {
                carToRemove = c;
            }
        }
        if (carToRemove != null) {
            carsArray.remove(carToRemove);
        } else {
            throw new IndexOutOfBoundsException();
        }
    }

    public void printCars() {
        if (isEmpty()) {
            System.out.println("Empty..");
        } else {
            for (Car c : carsArray) {
                c.printDetails();
            }
        }
    }

    public boolean isEmpty() {
        return carsArray.isEmpty();
    }

}

Car Class:

package CarPartsB;

public class Car {

    private double price;
    private int year_of_production;
    private String make;
    private String model;
    private int yearsOld;
    private int carID;
    static int CAR_ID;

    public Car(double price, int year_of_production, String make, String model) {
        this.price = price;
        this.year_of_production = year_of_production;
        this.make = make;
        this.model = model;
        this.yearsOld = 2018 - this.year_of_production;
        this.carID = CAR_ID;
        CAR_ID++;

    }

    public int getCarID() {
        return this.carID;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void setYear_of_production(int year_of_production) {
        this.year_of_production = year_of_production;
    }

    public void setMake(String make) {
        this.make = make;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public double getPrice() {
        return price;
    }

    public int getYear_of_production() {
        return year_of_production;
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public void printDetails() {
        System.out.println("ID:" + this.carID + " " + this.make + " "
                + this.model + " is " + this.yearsOld + " "
                + "years old and has price of " + this.price);
    }

}
\$\endgroup\$
  • \$\begingroup\$ Do not change the code in the question after receiving an answer. Incorporating advice from an answer into the question violates the question-and-answer nature of this site. See What should I do when someone answers my question for alternatives. I have rolled-back the edit for you. \$\endgroup\$ – AJNeufeld Oct 23 '18 at 20:09
0
\$\begingroup\$

Car

Your Car class has what I would consider deficiencies.

The make, model, year_of_production and carId shouldn’t change after creating a car. They should be final. Attributes like the price (and colour and condition) of the car can change.

Inconsistent usage of this.. The function getCarID() doesn’t need it.

Bug: The method setYear_of_production doesn’t change the yearsOld member!!!

The constructor uses a hard-coded 2018.

The yearsOld member should not be a member at all, but a getter method which relies on the year of production and the current year. If after putting cars on the list, a year goes by, the cars current don’t (and can’t) age! If you haven’t learnt how to query the current year, at least use a parameter or a global static (volatile, not constant) value.

Your Car class is a data model class. It shouldn’t have “output” functions. The class could be used by a console application or a GUI application. “Debug” output is fine, but don’t print output if you can avoid it. And you can. Write a Car.toString() function, and the caller could System.out.println(car). Or better, add a printCarDetails() in CarPartsMenu. For the same reasons, I’d move printCars() out of CarsArray (a data model class) into CarPartsMenu.


CarsArray

The carsArray should be final.

.getCars(), .size(), and .addCar() all unnecessarily use this..

IndexOutOfBoundsException is not the right exception to use. NoSuchElementException is a better semantic match.


\$\endgroup\$
  • \$\begingroup\$ Thank you for your feedback. I have modified code in my question to reflect changes that you mentioned. Are there any other things you would suggest on improving? \$\endgroup\$ – thisGuyCodes Oct 23 '18 at 20:03
  • \$\begingroup\$ I have rolled-back your edit to the original question. See the "I improved my code based on the reviews. What next?" section of What should I do when someone answers my question? for information on how to create followup questions when you want additional feedback after incorporating changes. \$\endgroup\$ – AJNeufeld Oct 23 '18 at 20:12
0
\$\begingroup\$

I have modified my code to the suggestions, what are other things that could be worked on? Thank you for your help.

Car Menu:

package CarPartsB;

import java.util.InputMismatchException;
import java.util.Scanner;

public class CarPartsMenu {

    Scanner console = new Scanner(System.in);
    private final CarsArray carsList = new CarsArray();
    private boolean loopVariable = true;

    public void showMenu() {

        while (loopVariable) {
            try {
                System.out.println("1: Add car.\n2: Remove car.\n3: List cars.\n4: Exiting");
                int userInput = console.nextInt();
                switch (userInput) {
                    case 1:
                        addCar();
                        break;
                    case 2:
                        removeCar();
                        break;
                    case 3:
                        listCars();
                        break;
                    case 4:
                        loopVariable = false;
                        break;
                }
            } catch (InputMismatchException e) {
                console.nextLine();
                System.out.println("\n" + e + " \nhas happened, choose value from 1 o 4.\n Click enter to continue...");
                console.nextLine();
            }
        }
    }

    private void addCar() {
        String make, model;
        int year;
        double price;
        try {
            System.out.println("What's price of your car? ");
            price = console.nextDouble();
            validateInput(price);
            System.out.println("What year was your car made?");
            year = console.nextInt();
            validateInputYear(year);
            System.out.println("What's the make of your car?");
            make = console.next();
            System.out.println("What's the model of your car?");
            model = console.next();
            Car car = new Car(price, year, make, model);
            carsList.addCar(car);
        } catch (InputMismatchException e) {
            console.nextLine();
            System.out.println("\n" + e + "\nhas happened, make sure to input correct values.\n Click enter to continue...");
            console.nextLine();
        }
    }

    private void removeCar() {
        if (carsList.isEmpty()) {
            console.nextLine();
            System.out.println("There are no cars in the list");
            console.nextLine();
        } else {
            try {
                System.out.println("Type id of the car you want to remove: ");
                int userInputID = console.nextInt();
                carsList.removeCar(userInputID);
                System.out.println("Car with ID: " + userInputID + " has been removed.\n");
                console.nextLine();
            } catch (IndexOutOfBoundsException e) {
                console.nextLine();
                System.out.println("\n" + e + "\nhas happened, you have to pick ID that EXISTS.\n Click enter to continue...");
                console.nextLine();
            } catch (InputMismatchException e) {
                console.nextLine();
                System.out.println("\n" + e + "\nhas happened, input an integer.\n Click enter to continue...");
                console.nextLine();
            }
        }
    }

    private void listCars() {
        console.nextLine();
        System.out.println("List of cars: ");
        printCarDetails();
        System.out.println("\nPress anything to continue...");
        console.nextLine();
    }

    private void printCarDetails() {
         if (carsList.isEmpty()) {
            System.out.println("Empty..");
        }else {
            for(Car c : carsList.getCars()) {
                System.out.println("ID:" + c.getCarID() + " " + c.getMake() + " "
                + c.getModel() + " is " + c.getYearsOld() + " "
                + "years old and has price of " + c.getPrice());
            }
         }

    }

    private void validateInputYear(int number) {
        if (number < 1900 || number > 2018) {
            throw new InputMismatchException("\nYou can't add car that was made earlier than 1900\n or after 2018");
        }
    }

    private void validateInput(double number) {
        if (number <= 0) {
            throw new InputMismatchException("\nPrice can't be negative or zero.");
        }
    }

}

Array Class

package CarPartsB;

import java.util.ArrayList;
import java.util.NoSuchElementException;

public class CarsArray extends ArrayList {

    private final ArrayList<Car> carsArray;

    public CarsArray() {
        this.carsArray = new ArrayList();
    }

    public ArrayList<Car> getCars() {
        return carsArray;
    }

    public int size() {
        return carsArray.size();
    }

    public void addCar(Car element) {
        carsArray.add(element);
    }

    public void removeCar(int carId) {
        Car carToRemove = null;
        for (Car c : carsArray) {
            if (c.getCarID() == carId) {
                carToRemove = c;
            }
        }
        if (carToRemove != null) {
            carsArray.remove(carToRemove);
        } else {
            throw new NoSuchElementException();
        }
    }

    public boolean isEmpty() {
        return carsArray.isEmpty();
    }

}

Car Class

package CarPartsB;

import java.time.Year;

public class Car {

    private double price;
    private final int year_of_production;
    private final String make;
    private final String model;
    private final int yearsOld;
    private final int carID;
    static int CAR_ID;
    int year = Year.now().getValue();


    public Car(double price, int year_of_production, String make, String model) {
        this.price = price;
        this.year_of_production = year_of_production;
        this.make = make;
        this.model = model;
        this.yearsOld = year - this.year_of_production;
        this.carID = CAR_ID;
        CAR_ID++;

    }

    public int getYearsOld() {
        return yearsOld;
    }

    public int getCarID() {
        return carID;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    public int getYear_of_production() {
        return year_of_production;
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.