我的主要课程代码
{
ArrayList<Item> items = new ArrayList<Item>();
Scanner file = new Scanner(kk.class.getResourceAsStream("product.txt"));
while (file.hasNextLine()) {
String[] sp = file.nextLine().split(",");
// extract item number, description, price and type
itemNum = Integer.parseInt(sp[0]);
des = sp[1];
price = Integer.parseInt(sp[2]);
Item objt = new Item(itemNum, des, price); // Creating a new object
items.add(objt); // Adding it to the list
}
System.out.println(items);
}
输出我正在
[dada.Item@4a5d4a62,dada.Item @ 32be8e12,dada.Item @ 7c6159c4,dada.Item @ 5b4c92a7,dada.Item @ 3040c5,
我的项目类代码
private int itemNum = 0;
private String des = "";
private int price = 0;
public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}
答案 0 :(得分:2)
您正在打印Item
引用的地址,而不是Item
对象中的字段。您可以通过循环遍历每个Item
对象中的字段。
替换此行
System.out.println(items);
带
for(Item i : items)
{
System.out.println(i.getItemNum()+" "+i.getDes()+" "+i.getPrice());
}
更改课程,以便您可以访问您的私人字段
private int itemNum = 0;
private String des = "";
private int price = 0;
public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}
public void setItemNum(int itemNum) {
this.itemNum = itemNum;
}
public int getItemNum() {
return itemNum;
}
public void setDes(String des) {
this.des = des;
}
public String getDes() {
return des;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}