0

How to create an instance variable called passengers which is an array of references to person objects. the length of the array represents the number of passengers that the vehicle can hold i.e. the capacity of the vehicle which is given as a parameter to the constructor.

This is what i have done so far

public class Vehicle{

  private String LicensePlateNum, make, model;
  private int year, NumOfDoors, NumOfWheels;
  private Person driver;
  private Person [] passengers;
  private int NumOfPassengers;
  private int capacity;



   public Vehicle(String LicensePlateNum, String make, String model, int     year, int NumOfDoors, int NumOfWheels, int capacity){
    this.LicensePlateNum=LicensePlateNum;
    this.make=make;
    this.model=model;
    this.year=year;
    this.NumOfDoors=NumOfDoors;
    this.NumOfWheels=NumOfWheels;
    this.capacity=capacity;
    NumOfPassengers=0;
    driver=null;
    passengers=new Person[capacity];
  }
FredPeter
  • 1
  • 5
  • Well, which bit is causing you a problem? Do you know how to declare an instance variable of an array type? Do you know how to create an array object with a specific capacity? Please show what you've tried, and where you're stuck. – Jon Skeet Sep 23 '16 at 16:14
  • @JonSkeet i am having a problem creating the instance variable which is an array of references, and passing the capacity as a parameter to the constructor. i know that declaring an array takes the following form; – FredPeter Sep 23 '16 at 22:53
  • @JonSkeet i am having a problem creating the instance variable which is an array of references, and passing the capacity as a parameter to the constructor. i know that declaring an array takes the following form: elementType[]arrayName={value1,value2...} – FredPeter Sep 23 '16 at 22:54
  • Well that's how you create *and populate* an array. The code in your question would work if capacity were defined somewhere.... But you need to make that a constructor parameter, and change the code to only declare the variable (without assigning it a value) where it is now, and assign the value in the constructor. – Jon Skeet Sep 24 '16 at 06:32
  • Thank you. Please how would i call the array 'passengers' in my main function and enter an int for the capacity?@JonSkeet – FredPeter Sep 25 '16 at 02:05
  • You've already done it. `passengers=new Person[capacity];` – user207421 Sep 25 '16 at 02:10
  • @FredPeter: You don't "call" the array - you call the *constructor* that you define, passing in `capactiy`. As for how you enter the `int` for the capacity... you could use a hard-coded value, or ask the user... that's a different matter. Currently you've got a field for capacity. You don't need that - you *only* need it as a constructor parameter, and then use it to initialize the arrya. – Jon Skeet Sep 25 '16 at 07:18

0 Answers0