java arraylist 取值,如何在ArrayList java中获取值

这篇博客讨论了如何从ArrayList中获取Car对象,并计算所有汽车的总价格。代码示例展示了如何遍历ArrayList,调用每个Car对象的computeCars()方法来计算总价,然后将这些值累加到总金额上。在Car类中,新增了一个方法用于计算包含税的价格。
摘要由CSDN通过智能技术生成

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 cars = new ArrayList();

cars.add(toyota);

cars.add(nissan);

cars.add(ford);

}

public static void processCar(ArrayList cars){

// in heare i need a way of getting the total cost of all three cars by calling

// computeCars ()

System.out.println(cars.get());

}

revision

thanks 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 cars){

int totalAmount=0;

for (int i=0; i

cars.get(i).computeCars ();

totalAmount=+ ?? // in need to add the computed values of totalprice from the Car class?

}

}

Thanks again

解决方案

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

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

where i is the index of the element.

You can also use

Car c = car.get(i);

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

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

main

public static void processCar(ArrayList cars){

int totalAmount=0;

for (int i=0; i

int totalprice= cars.get(i).computeCars ();

totalAmount=+ totalprice;

}

}

And change the return type of your function

public int computeCars (){

int totalprice= price+tax;

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

return totalprice;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值