我試圖從ArrayList
中得到一個值。我有兩個班級,主要和Car類。這裏是代碼:從ArrayList中獲取值java
public class CarOrders {
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){
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?
}
System.out.println (totalAmount);
}
}
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);
}
}
我怎麼能夠在processCar()
法計算totalAmount
其中totalAmount=totalAmount+totalPrice
從computCar()
方法在汽車類?
使'computeCars()'返回'totalprice'。因此'totalAmount + = cars.get(i).computeCars()'; – Reno