初始化一个int数组元素的字符串
问题描述:
我想创建一个toString方法,它会返回我的对象“Individual”的字符串表示形式。个体是一个整数数组。该字符串应包含我的排列的介绍,以及数组的索引和元素。初始化一个int数组元素的字符串
所以理想的字符串应该是这样的
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表示形式,特别是对如何存储元素的数组到字符串。
答
你需要一个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();
}
答
您可以存储数组元素融入这样的字符串,如果你的意思是这样的:
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;
什么是'individual'?显示代码。 – 2015-02-08 17:55:43
你可以包括输入和预期输出的例子吗? – Pshemo 2015-02-08 17:57:41
所以你需要一个索引字符串,并在它下面有一个int值的字符串,问题是要对齐它们吗? – 2015-02-08 17:58:57