[英]How to control the returning array from a method by a way similar to toString()
我有一个关于返回数组的问题。 我希望数组准备好打印,而无需使用while循环来打印其元素。
当数组是类中的实例变量时,可以通过覆盖.toString()来执行此操作。 但是,我不知道如何返回数组。 我只是在main方法中使用了while循环来单独打印每个元素。 我的目标是仅通过使用以下语句自动执行此操作:
System.out.println("Largest stock items: " + shop.largestStockItems(FILTERING_VALUE));
并自动获得结果:
Largest stock items:
Code: c03
Name: jug
Price: 8.000
Quantity: 75
Code: c01
Name: mug
Price: 0.900
Quantity: 60
那么,我对largestStockItems()或任何其他方法(如果有)可以做哪些更改?
这是我实际上拥有的(我不想要的):
主要:
//display the largest stock items
System.out.println("Largest stock items: ");
Item[] largestStockItemsList = shop.largestStockItems(FILTERING_VALUE);
for (Item item : largestStockItemsList){
System.out.println(item);
}
Shop类中的maximumStockItems():
/**
* Get the list of largest stock of items
* @param value the value to which the item is checked
* @return the list of largest stock of items
*/
public Item[] largestStockItems(double value){
Filter[] filtered = Data.filterItems(Arrays.copyOf(items,currentSize), value);
return Arrays.copyOf(filtered,filtered.length,Item[].class);
}
这是Item类中的.toString方法:
/**
* Returns the description of the item
* @return the description of the item
*/
public String toString() {
return "Code: " + id
+ "\nName: " + name
+ "\nPrice: " + String.format("%.3f", price)
+ "\nQuantity: " + quantity +"\n";
}
下面的解决方案应该工作:
System.out.println("Largest stock items: " + Arrays.toString(shop.largestStockItems(FILTERING_VALUE)));
如果您需要以问题中提到的格式打印,请尝试以下代码:
System.out.println(Arrays.stream(shop.largestStockItems(FILTERING_VALUE)).map(Item::toString).collect(Collectors.joining("\n\n")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.