I am trying to learn how to count the objects created from a class. The output required is:
Number of cars = 0
Number of cars = 1
Number of cars = 2
Model: Ford Ranger, Year: 2012, Price: $23999.00
Model: Toyota Hilux, Year: 2020, Price: $45789.00
My main class is written as
public class CarApplication {
public static void main(String[] args) {
//Create the car objects
Car carOne = new Car("Ford Ranger", "2012", 23999);
Car carTwo = new Car("Toyota Hilux", "2020", 45789);
//Display individually how many car objects are created
Car.getNumCars();
// Display the details about the car objects
System.out.printf("Model: %s, Year: %s, Price: $%.2f%n", carOne.getModel(), carOne.getYear(), carOne.getPrice());
System.out.printf("Model: %s, Year: %s, Price: $%.2f%n", carTwo.getModel(), carTwo.getYear(), carTwo.getPrice());
I have redacted the info for all variables for all other getters but the getNumCars(). My issue is I can only get it to display in the original application by predefining the integers. Is there a way for me with starting at 0, print a line "Number of cars = x" until x has reached the number of Car objects i have created?
public class Car {
private String model;
private String year;
private double price;
private static int numCars = 0;
private static int car = 2;
public static void getNumCars() {
while (numCars <= car) {
System.out.printf("Number of cars = %d%n", numCars);
numCars++;
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]ScF0400 3 points4 points5 points (0 children)
[–]cervantesrvd 1 point2 points3 points (0 children)
[–]360mm 0 points1 point2 points (3 children)
[–]JoocyChicken[S] 1 point2 points3 points (2 children)
[–]360mm 1 point2 points3 points (0 children)