你需要在toString()
你的类中添加一个方法
public class Car {
private String make;
private String model;
public void setMake (String str1) {
make = str1;
}
public void setModel (String str2) {
model = str2;
}
@Override
public String toString() {
return "Make :"+ make + " Model :" + model;
}
}
只是打印一辆车
然后您可以按如下方式使用它
public static void main(String[] args){
Car car=new Car();
car.setMake("Audi");
car.setModel("ModelName");
System.out.println(car);
}
打印所有数组
同样,如果这存在于一系列汽车中(为了简洁起见,我正在使用我在注释中介绍的构造函数)
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
for(int i=0;i<cars.length;i++){
System.out.println(cars[i]);
}
}
用户选择索引后打印
public static void main(String[] args){
Car[] cars=new Car[3];
cars[0]=new Car("Audi","ModelName");
cars[1]=new Car("BMW","ModelName");
cars[2]=new Car("Honda","ModelName");
Scanner scan=new Scanner(System.in);
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
//checks that user actually inputs an integer,
//checking its in range is left as an excercise
while (scan.hasNextInt()==false){
scan.next(); //consume bad input
System.out.println("Select index to print, should be between 0 and " + (cars.length-1));
}
int index=scan.nextInt();
System.out.println(cars[index]);
}
笔记
似乎品牌和型号对于汽车类的工作至关重要,请考虑更改您的构造函数以将它们作为参数
public Car(String make, String model){
this.make=make;
this.model=model;
}
所有这些都假设您已经拥有要打印的元素