我正在尝试创建一个 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/