I'm new at Java and I'm trying to create an array of objects without using the collection ArrayList. What I want to do is to create an array of objects for constructor "Passenger" class in main class and instantiate it in class SubwayManager in method "showPassenger" where I can return a specific Passenger with a given name passed by parameter but I don't have any idea how I can do this. Would really appreciate any help.
Here's my Passenger class:
public class Passenger {
private String name;
private String nif;
private String birthDate;
private boolean student;
public Passenger(String name, String nif, String birthDate) {
this.name = name;
this.nif = nif;
this.birthDate = birthDate;
this.student = false;
}
Here's the main class where I created the array of Passengers objects:
public class IPOO_P2 {
private static Passenger[] passengers = new Passenger[10];
public static void main(String[] args) {
SubwayManager man1 = new SubwayManager();
for(int i=0; i<passengers.length; i ){
passengers[0] = new Passenger("nomee", "298282928", "29-12-2022");
passengers[1] = new Passenger("nomee2", "2982829281", "29-12-2021");
passengers[2] = man1.createPassenger("name", "nif", "birthdate");
}
man1.showPassenger("nomee");
}
}
And here's the class SubwayManager where I want to use the array of Passengers:
public class SubwayManager {
private DataBase db;
private Menu menu;
private Passenger[] passengers;
public SubwayManager() {
this.db = new DataBase();
this.menu = new Menu(this);
passengers = new Passenger[10];
}
//the method where I want to instantiate and use the array of Passengers
public void showPassenger(String name) {
for (int i = 0; i < passengers.length; i ) {
if (passengers[i].getNif().equals(name)) {
System.out.println(passengers[i].toString());
}else{System.out.println("There isn't any passenger with that name");
}
}
}
CodePudding user response:
Use a parameterized subway manager constructor. Put your passenger array in it. Then your show passenger method should work.