【发布时间】:2020-12-31 01:06:10
【问题描述】:
我正在尝试从 ArrayList 中获取值。这是我的代码示例:
public static void main (String [] args){
Car toyota= new Car("Toyota", "$10000", "300"+ "2003");
Car nissan= new Car("Nissan", "$22000", "300"+ "2011");
Car ford= new Car("Ford", "$15000", "350"+ "2010");
ArrayList<Car> cars = new ArrayList<Car>();
cars.add(toyota);
cars.add(nissan);
cars.add(ford);
}
public static void processCar(ArrayList<Car> cars){
// in heare i need a way of getting the total cost of all three cars by calling
// computeCars ()
System.out.println(cars.get());
}
修订 谢谢大家的回答,我可能应该多加一点代码。在 Car 类中,我有另一种方法来计算包括税在内的总成本。
class Car {
public Car (String name, int price, int, tax, int year){
constructor.......
}
public void computeCars (){
int totalprice= price+tax;
System.out.println (name + "\t" +totalprice+"\t"+year );
}
}
在主类中
public static void processCar(ArrayList<Car> cars){
int totalAmount=0;
for (int i=0; i<cars.size(); i++){
cars.get(i).computeCars ();
totalAmount=+ ?? // in need to add the computed values of totalprice from the Car class?
}
}
再次感谢
【问题讨论】:
标签: java