所以我有這個類叫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