我有一个物品类,包含诸如itemName、price等数据,当卖家想要销售某些物品时,我会向其中添加数据,如下所示:
public void sellItem(String itemName, double Price) throws java.rmi.RemoteException, Exception {
items.add(new Item(itemName, price));
然后我将列表中的所有项目返回,以便卖家/买家可以浏览列表。
public ArrayList<Item> listItems() {
return items;
}
接下来,我正在努力填充JGroups实例,以便允许此“项”数据在实例之间进行复制。当一个项目被列出时,我将其转换为一个对象:
/* Create a new ItemObject containing the Items used for JGroups later */
public void createItemObject() throws Exception {
Object[] objArray = items.toArray();
FileOutputStream fis = new FileOutputStream("io");
ObjectOutputStream itemObject = new ObjectOutputStream(fis);
itemObject.writeObject(objArray);
itemObject.close();
fis.close();
}
每个复制服务器实例将以此对象作为输入,并希望将此对象中的数据打印到其终端窗口:
static Object io = new Object();
public static void getAuctionObject() throws Exception {
FileInputStream fis = new FileInputStream("io");
ObjectInputStream auctionObjectIn = new ObjectInputStream(fis);
ao = auctionObjectIn.readObject();
auctionObjectIn.close();
System.out.println("Received object at Front End: " + ao);
//Print out item data.....
}
然而,我该如何遍历此对象并打印出物品数据,例如“itemName”,“price”等等?
.toString()
方法可能会有帮助。然后你就可以直接调用.toString()
。 - ryanyuyu.toString()
进行基本调试。如果您对格式良好的字符串有不同的要求,请考虑添加一个新的字符串方法inventoryString()
或类似的内容,以按您需要的方式打印格式化的字符串。 - markspace