[英]Initializing a string with elements of an int array
我正在嘗試創建一個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");
}
我一直在堅持如何將特定的表示形式存儲為字符串並設置其格式,尤其是如何將數組元素存儲到字符串中。
您需要一個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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.