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

时间:2015-02-08 17:53:46

标签: java arrays string

我试图创建一个toString方法,该方法将返回我的对象​​的字符串表示" 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");
  }

我坚持如何将这个特定表示形式存储和格式化为String,尤其是如何将数组元素存储到字符串中。

2 个答案:

答案 0 :(得分:3)

您需要一个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();
  }

答案 1 :(得分:0)

如果您的意思是:

,您可以将数组元素存储到字符串中
String data = ""; // empty
ArrayList items; // array of stuff you want to store into a string

for(int i =0; i< items.size(); i++){
  data+=""+items.get(i) + ","; // appends into a string
} 

// finally return the string, you can put this in a function
return data;