所以我有这个类叫Product
存储有关产品的信息,特别是它的名称,它的价格和数量。它看起来像这样:如何存储并访问ArrayList中的类对象?
import java.util.Scanner;
public class Product {
private String name;
private int quantity;
private double price;
public Product(){
name = "";
quantity = 0;
price = 0.0;
}
public Product(String name, int prodQuantity, double prodPrice){
this.name = name;
quantity = prodQuantity;
price = prodPrice;
}
public void setProductName(String name){
this.name = name;
}
public boolean setProductQuantity(int prodquantity){
if(prodquantity < 0)
return false;
quantity = prodquantity;
return true;
}
public boolean setProductPrice(double prodPrice){
if(prodPrice < 0.0)
return false;
price = prodPrice;
return true;
}
public String getName(){
return name;
}
public int getQuantity(){
return quantity;
}
public double getPrice(){
return price;
}
public void setFromLine(String product){
StringTokenizer str = new StringTokenizer (product);
name = str.nextToken();
String quan = str.nextToken();
String p = str.nextToken();
price = Double.parseDouble(p);
quantity = Integer.parseInt(quan);
}
}
我想,然后使用setFromLine
方法从一个文件中的行阅读,一条线,看起来像
<product> <price> <quantity>
由空格分隔,并设置适当的领域给了那条线,这是应该做的。但是,那么我想将它存储在我的驱动程序中的ArrayList
字段中。现在,我有我的驱动程序的方法,看起来像这样:
public static void readFromFile(String filename) throws IOException {
File file = new File(filename);//File object opens file
Scanner inputFile = new Scanner(file);//Scanner object needed to read from file
balance = inputFile.nextDouble();
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
Product proInfo = new Product();
proInfo.setFromLine(line);
productInfo.add(proInfo);
}
inputFile.close();
}
所以,我的问题是:如果我的代码是正确的,我怎么去访问的信息,特定部分我存储在ArrayList
。例如,如果我想访问有关产品灯的信息,该产品的灯价格为15.3,数量为200,并且它是第一个读入文件并存储在ArrayList
中的产品,那么我可以编写哪些代码行来明确价格或它的数量而言,等我ArrayList
在我的驱动程序领域是这样的,顺便说一句:
ArrayList<Product> productInfo = new ArrayList<Product>();
'productInfo.get(0).getPrice()',以获得第一元件的价格。 – msfoster 2014-11-08 20:45:37
我不知道你的货币计算有多少准确度,但是如果你想要精度,'double'是不是... – fge 2014-11-08 20:48:53