2011-10-31 159 views
0

我試圖從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+totalPricecomputCar()方法在汽車類?

+0

使'computeCars()'返回'totalprice'。因此'totalAmount + = cars.get(i).computeCars()'; – Reno

回答

1

只是​​從computeCars()

public int computeCars() 
{ 
    return price+tax; 
} 

則:

public static void processCar(ArrayList<Car> cars){ 
     int totalAmount=0; 
     for (int i=0; i<cars.size(); i++){ 
     totalAmount+= cars.get(i).computeCars(); 
     } 
     System.out.println (totalAmount); 
    } 
1

我建議你改變你的computCar()方法

public int computeCar() { ... } 

的簽字,並經該方法調用返回totalPrice的價值。因此,您可以在您的方法processCar()中使用它。

0
public int computeCars() 
    { 
     return price+tax; 

    } 


public static void processCar(ArrayList<Car> cars){ 
     int totalAmount=0; 
     for (int i=0; i<cars.size(); i++){ 

     totalAmount=+ cars.get(i).computeCars(); 
     // in need to add the computed values of totalprice from the Car class? 

     } 
     System.out.println (totalAmount); 

    } 
-1

你需要在你車類的一些變化,它應該是這樣的:

class Car { 
//i'm adding only 2 properties you can add all the properties 
public int price; 
public int tax; 
public Car (String name, int price, int tax, int year) 
{ 
    //here you should add these 2 lines 
    this.price=price; 
    this.tax=tax; 
} 

和你f聯合將是:

public static void processCar(ArrayList<Car> cars){ 
    int totalAmount=0; 
    for (int i=0; i<cars.size(); i++){ 
     cars.get(i).computeCars(); 
    totalAmount=+ cars.get(i).price; 
    // in need to add the computed values of totalprice from the Car class? 

    } 
    System.out.println (totalAmount); 

}