本文介绍了如何在ArrayList java中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从ArrayList中获取值。以下是我的代码示例:

I am trying to get a value from with in an ArrayList. Here is a sample of my code:

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类中,我有另一种计算包括税收在内的总成本的方法。

revisionthanks all for the answers, I should probably add to the code a bit more. in the Car class, i have another method that is calculating the total cost including the tax.

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

主要类中的

in the main class

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

再次感谢

推荐答案

假设你的 Car 类有一个价格的getter方法,你可以简单地使用

Assuming your Car class has a getter method for price, you can simply use

System.out.println (car.get(i).getPrice());

其中 i 是元素的索引。

你也可以使用

Car c = car.get(i);
System.out.println (c.getPrice());

您还需要退回 totalprice 如果你需要存储它的功能

You also need to return totalprice from your function if you need to store it

main

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

并更改返回你的函数类型

public int computeCars (){
    int  totalprice= price+tax;
    System.out.println (name + "\t" +totalprice+"\t"+year );
    return  totalprice;
 }

这篇关于如何在ArrayList java中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:04