When I create several objects for my cars, I would like to enumerate my cars also…
For example:
---------------------- Car n ° **1** Mark : Opel Model : CDTI Number of doors : 3 Price : 7000 ---------------------- Car n ° **2** Mark : Mercedes Model : Classe A Number of doors : 5 Price : 10000 ----------------------
For now, I have this:
---------------------- Car n ° Mark : Opel Model : CDTI Number of doors : 3 Price : 7000 ---------------------- Car n ° Mark : Mercedes Model : Classe A Number of doors : 5 Price : 10000 ---------------------- Car n ° Mark : BMW Model : Seie 5 Number of doors : 5 Price : 15000
In my class Car
, I don’t understand how to create this loop ???
I tried this, but it’s not correct
public void display() { int i = 0; while (i < 10) { i++; } System.out.println("Car n ° " + i); System.out.println("Mark : " + mark); System.out.println("Model : " + model); System.out.println("Number of doors : " + nbDoors); System.out.println("Price : " + price); }
Here is my class Car
public class Car { public String mark; public String model; public int nbDoors; public int price; public Car(String mark, String model, int nbDoors, int price) { this.mark = mark; this.model = model; this.nbDoors = nbDoors; this.price = price; } public void display() { System.out.println("Car n ° "); System.out.println("Mark : " + mark); System.out.println("Model : " + model); System.out.println("Number of doors : " + nbDoors); System.out.println("Price : " + price); } }
Here is also my class Main
System.out.println("----------------------"); Car car1 = new Car("Opel", "CDTI", 3, 7000); car1.display(); System.out.println("----------------------"); Car car2 = new Car("Mercedes", "Classe A", 5, 10000); car2.display();
Thank you a lot for your help.
Answer
If you are allowed to use the Collections, you should consider using an ArrayList rather than an array. That way you don’t have to know how many cars will be in the array, or create the cars in advance like you do with an array.
The loop part is a simple for each loop that loops through the collection:
EDIT: Added a counter so each car receives an index. This also required the .display()
method to change to receive the index.
public static void main(String[] args) { List<Car> cars = new ArrayList<Car>(); cars.add(new Car("Opel", "CDTI", 3, 7000)); cars.add(new Car("Mercedes", "Classe A", 5, 10000)); int counter = 0; for(Car car : cars) { car.display(counter++); } }
Here is a working sample: https://replit.com/@randycasburn/scratch-java