我正在尝试格式化程序的输出,因此用户可以轻松阅读。我不擅长格式化文本,我真的很欢迎你的帮助。
我正在尝试打印/显示(在我的JTextArea中)。我已经有了一种显示方法:
public void display(String... lines){
for(String line:lines){
System.out.println(line);
}
}
现在,我有2个包含一些数据的ArrayLists,这些数据是通过使用该程序添加到它们的。
itemOrders = new ArrayList<CafeOrders>();
customers = new ArrayList<CafeCustomer>();
构造函数分别为:
public CafeOrders(String orderID, String itemName, double price){
super();
this.orderID = orderID;
this.itemName = itemName;
this.price = price;
}
和
public CafeCustomer(int customerID, String customerName){
super();
this.customerID = customerID;
this.customerName = customerName;
this.orderNo = UUID.randomUUID().toString();
}
我是这样做的,即orderNo = orderID 首先询问客户名称,然后当他从项目列表中选择时,每个项目都与客户的ID一起添加到CafeOrders ArrayList。
我想创建一个以特定格式打印这两个ArrayLists的方法,或类似的东西:
customerName "with id" orderID "has purchased" itemName1
itemName2
itemName3
etc...
任何帮助将不胜感激!
答案 0 :(得分:0)
for(CafeCustomer customer : customers ){
for(CafeOrders order: itemOrders ){
if(customer.getOrderNo.equals(order.getOrderId()) ){
System.out.println(customer.getCustomerName() +"with Id " +
customer.getCustomerId() + "has purchased "
+order.getItemName());
}
}
}
答案 1 :(得分:0)
只要您的客户可以拥有多个订单,我建议您使用
Map<CafeCustomer, List<CafeOrder>>
然后你能做什么:
public void display(Map<CafeCustomer, List<CafeOrder>> map)
{
map.forEach( (customer, orderList) -> {
System.out.println(customer.getCustomerName() + " has purchased:");
for(CafeOrder order : orderList)
System.out.println(order.getItemName());
});
}
答案 2 :(得分:0)
为特定格式编辑
向@Shiksha Verma添加额外代码,仅打印一次客户名称和ID:
int x = 0;
for(CafeCustomer customer : customers ){
for(CafeOrders order: itemOrders ){
if(customer.getOrderNo.equals(order.getOrderId()) ){
if(x == 0){
System.out.println(customer.getCustomerName() +"with Id " +
customer.getCustomerId()+ "has purchased: "
+order.getItemName());
x = 1;
continue;
}
System.out.printf("%1$40s",order.getItemName());
}
}
x = 0;
}
答案 3 :(得分:0)
虽然此代码有效:
public void displayOrders(){
for(CafeCustomer customer : customers ){
for(CafeOrders order: itemOrders ){
if(customer.getOrderNo().equals(order.getOrderID()) ){
display(customer.getCustomerID()+"."+customer.getCustomerName() +"with Order ID " +
customer.getOrderNo() + " has purchased a "
+order.getItemName());
}
}
}
}
我希望客户ID,名称和订单ID出现一次,然后出现在项目列表的右侧。就像我在最初的帖子中所展示的那样 可能吗?我似乎无法找到办法。 像这样:
customerID"."customerName "with id" orderID "has purchased" itemName1
itemName2
itemName3
etc...
看起来就像这样。
答案 4 :(得分:0)
修改代码如下:
for(CafeCustomer客户:客户){
System.out.println(customer.getCustomerName() +"with Id " +
customer.getCustomerId()+ "has purchased ::");
for(CafeOrders order: itemOrders ){
if(customer.getOrderNo.equals(order.getOrderId()) ){
System.out.println("\t\t\t\t\t\t\t"+ order.getItemName());
}
}
}