简体   繁体   中英

reading information from an array of objects filled with arrays of different data types

I've created an array of objects, with 5 different arrays primarily containing integers and strings (names of people and vehicle types). My question is once I've created an object array, how do I display the information pertaining to a selected index?

class Vehicle
{
    int passengers, fuelCapacity, mpg;
    String type, name;

    Vehicle(String n, String t, int p, int f, int m)
    {
        passengers = p;
        fuelCapacity = f;
        mpg = m;
        type = t;
        name = n;
    }

    int range()
    {
        return mpg * fuelCapacity;
    }

}

// Declaring Vehicles array for the pertinent information.
Vehicle[] iVehicles = new Vehicle[10];

// array consisting of the types of vehicles.
String[] types = {"Truck", "Sportscar", "SUV", "Sedan", "Coupe", "Truck","Truck", "Sportscar", "SUV", "Sedan"};

// array consisting of the number of passengers per vehicle.
int[] nmbrOfPassengers = {2,2,8,4,4,4,2,2,7,4};

// array consisting of each vehicles fuel capacity in gallons.
int[] fuelCapacity = {15,15,20,20,12,15,19,19,16,10};

//array consisting of integers containing each vehicles miles per gallon.
int[] milesPerGallon = {20,18,13,35,31,34,39,19,22,25};


// array consisting of the names
String[] aNames = { "brian","bob","fred","janet","claire","bill","rudy","sandy","samuel","joan"};

for (int i = 0; i < iVehicles.length; i++)
{
    iVehicles[i] = new Vehicle(aNames[i], types[i], nmbrOfPassengers[i], fuelCapacity[i], milesPerGallon[i]);
}

// This is the portion i'm stumped on.
System.out.print(iVehicles[1]);

In order to display the information pertaining to a selected index the code is:

System.out.println(iVehicles[index])

However, System.out.println will automatically call toString method of class Vehicle. Unless you have override it, the default implementation (inherited from Object class) is useless for an user. So, in order to display the information you should provide a custom implementation of this method, in which you concatenate in a String, the values from the Vehicle attributes that you want to display.

You can print like this:

System.out.print(iVehicles[1].passengers);
System.out.print(iVehicles[1].fuelCapacity);
System.out.print(iVehicles[1].mpg);
System.out.print(iVehicles[1].type);
System.out.print(iVehicles[1].name);

Or

in your class Vehicle override the toString() method:

public String toString() { 
    return ("Passengers: " + this.passengers); // Concatenate all other fields.
} 

Now System.out.println(iVehicles[1]) will print what the toString() returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM