【问题标题】:how to return filled array item in user defined class toString method?如何在用户定义的类 toString 方法中返回填充的数组项?
【发布时间】:2020-04-03 23:30:06
【问题描述】:

该方法应该从数组中返回所有已填充的项,但它会返回数组中的最后一项。

public String toString() {

String result = "";

      for( int i = 0; i < list.length; i++ )
      {
         result =  String.format("%d. %s\n", i+1, list[i]);  
      }
      return result; 
   }

【问题讨论】:

  • 也许用+= 替换=!

标签: java arrays class tostring


【解决方案1】:

因为你总是用最新的替换result 字符串中的值

result =  String.format("%d. %s\n", i+1, list[i]);  // replaces the value always with latest 

所以使用 StringBuilder 附加所有值然后返回它

public String toString() {

 StringBuilder builder = new StringBuilder();

  for( int i = 0; i < list.length; i++ )
  {
     builder.append(String.format("%d. %s\n", i+1, list[i]));  
  }
  return builder.toString(); 
}

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 2014-08-12
    • 2023-03-21
    • 2019-04-21
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多