如何在ArrayList Java中获取值

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

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

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

}

}

在主要班级

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课程有价格的吸气剂方法,则可以简单地使用

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

i元素的索引在哪里。

您也可以使用

Car c = car.get(i);

System.out.println (c.getPrice());

totalprice如果需要存储,还需要从函数中返回

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;

}

}

并更改return您的功能类型

public int computeCars (){

int totalprice= price+tax;

System.out.println (name + "\t" +totalprice+"\t"+year );

return totalprice;

}

以上是 如何在ArrayList Java中获取值 的全部内容, 来源链接: utcz.com/qa/427472.html

回到顶部