【问题标题】:How to control the returning array from a method by a way similar to toString()如何通过类似于 toString() 的方式控制方法的返回数组
【发布时间】:2019-04-21 18:50:39
【问题描述】:

我有一个关于返回数组的问题。我希望数组准备好打印而不使用 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

那么,我可以用 largeStockItems() 或任何其他方法(如果有的话)做些什么改变?

这是我实际拥有的(我不想要的):

主要:

//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 类中的 largestStockItems():

/**
 * 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";
}

【问题讨论】:

  • 写一个辅助方法来做
  • 已经有一个辅助方法:Arrays.toString(Object[])。但你可能不喜欢它的格式,所以你最终还是要自己写。
  • @KevinAnderson 怎么办?
  • @user7 你是什么意思?
  • 移动逻辑循环和打印内容到方法并调用方法。

标签: java arrays class methods tostring


【解决方案1】:

以下解决方案应该有效:

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")));

【讨论】:

  • 这将以带括号的默认格式打印。我希望它采用上面显示的格式。
  • stream 是我能找到并且工作成功的唯一方式。我已经更新了我的答案。
  • @Noussa 这对你有用吗?你有什么更好的方法吗?
猜你喜欢
  • 2023-03-21
  • 2017-01-02
  • 2020-11-28
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 2020-04-03
  • 2018-04-16
  • 2023-03-22
相关资源
最近更新 更多