我创建了一个对象数组,有5个不同的数组,主要包含整数和字符串(人名和车辆类型)。我的问题是,一旦我创建了一个对象数组,如何显示与所选索引相关的信息?
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]);
答案 0 :(得分:1)
为了显示与所选索引有关的信息,代码为:
System.out.println(iVehicles[index])
但是,System.out.println
会自动调用类Vehicle的toString
方法。除非您覆盖它,否则默认实现(继承自Object类)对用户来说是无用的。
因此,为了显示信息,您应该提供此方法的自定义实现,在该方法中,您可以在String中连接,以及要显示的Vehicle属性中的值。
答案 1 :(得分:0)
您可以这样打印:
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);
或
您的class Vehicle
覆盖toString()
方法:
public String toString() {
return ("Passengers: " + this.passengers); // Concatenate all other fields.
}
现在System.out.println(iVehicles[1])
将打印toString()
返回的内容。