繁体   English   中英

从ArrayList Java获取值

[英]Getting a value from an ArrayList java

我正在尝试从ArrayList获取值。 我有两个班级,主要班和汽车班。 这是代码:

  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 );
     }

}

totalAmount中的processCar()方法中,其中的totalAmount=totalAmount+totalPrice ,如何在computCar()方法中计算totalAmount

我建议您更改computCar()方法的签名

public int computeCar() { ... }

并从此方法调用返回totalPrice作为值。 因此,您可以在您的方法processCar()使用它。

只需return price+tax; 来自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);
    }
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);

    }

您需要在Car类中进行一些更改,它应该像这样:

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;
 }

您的功能将是:

  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);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM