java - 使用 int 数组的元素初始化字符串

标签 java arrays string

我正在尝试创建一个 toString 方法,该方法将返回我的对象​​“Individual”的字符串表示形式。 individual 是一个整数数组。该字符串应包含对我的排列的介绍,以及数组的索引和元素。

所以理想情况下字符串应该是这样的

  public String toString() {
    System.out.println ("The permutation of this Individual is the following: ");
    for (int i=0; i<size; i++){
      System.out.print (" " + i);
    }
    System.out.println();
    for (int i=0; i<size; i++) {
      System.out.print (" " + individual[i]);
    }
    System.out.println ("Where the top row indicates column of queen, and bottom indicates row of queen");
  }

我一直困惑于如何将这个特定的表示形式存储和格式化为字符串,尤其是如何将数组元素存储到字符串中。

最佳答案

您需要一个 StringBuilder 而不是将其打印出来

 public String toString() {
    StringBuilder builder =new StringBuilder();
    builder.append("The permutation of this Individual is the following: ");
    builder.append("\n");//This to end a line
    for (int i=0; i<size; i++){
       builder.append(" " + i);
    }
    builder.append("\n");
    for (int i=0; i<size; i++) {
       builder.append(" " + individual[i]);
    }
    builder.append("\n");
    builder.append("Where the top row indicates column of queen, and bottom indicates row of queen");
    builder.append("\n");
    return builder.toString();
  }

关于java - 使用 int 数组的元素初始化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397291/

相关文章:

java - 纪念品模式无法正常工作

java - Play Framework : Submit button doesn't seem to work

python - Numpy 删除重复的列值

C++,在字符串的特定位置插入子字符串

c# - 在 C# 的 string[] 数组中插入字符串

python - 删除字符串中重复字符(单词)的最佳方法?

java - 如何将波形(用正弦波制成)从图片顶部移动到底部?

java - 从二叉搜索树中删除节点

c - 为什么当只使用一种格式说明符时数组显示垃圾值?

php - 连接 2 个 echo 并用逗号分隔 - 内爆、数组