java - 从 ArrayList java 获取值

标签 java

我正在尝试从 ArrayList 中获取值。我有两个类(class),主要类(class)和汽车类(class)。这是代码:

  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 Car 类中的 () 方法?

最佳答案

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

关于java - 从 ArrayList java 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7951282/

相关文章:

java - 如何分析 LAN 上运行的 Java 应用程序?

java - 注册页面、Toast 和 Firebase

java - 检查 ProcessBuilder 的参数是否是有效的命令

java - 如何在 Spring Boot 应用程序中实例化日志

java - 使用 Protocol Buffer 作为一般数据对象?

java - GCM 注销导致应用程序崩溃

java - java中有没有办法在windows系统中查询特定的程序窗口?

java - Admob 广告无法根据屏幕方向正确调整大小 [包括图片]

java - Scheduled Executor Service 只运行一次,没有抛出异常

java - SpringFox Swagger 与 Springboot 应用程序集成