0

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");
            }
        }

    }

1 Answer 1

2

Use a parameterized subway manager constructor. Put your passenger array in it. Then your show passenger method should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.