2015-02-08 46 views
0

我想創建一個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表示形式,特別是對如何存儲元素的數組到字符串。

+1

什麼是'individual'?顯示代碼。 – 2015-02-08 17:55:43

+2

你可以包括輸入和預期輸出的例子嗎? – Pshemo 2015-02-08 17:57:41

+0

所以你需要一個索引字符串,並在它下面有一個int值的字符串,問題是要對齊它們嗎? – 2015-02-08 17:58:57

回答

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(); 
    } 
+0

一般來說,我們讓用戶決定他是否想在它後面用行分隔符打印一些值。換句話說,'toString'的結果不應該在結果的末尾加上'\ n',所以考慮去掉'builder.append(「\ n」);'放在'return'語句之前。 – Pshemo 2015-02-08 18:21:30

+0

太酷了!謝謝你解決了我的問題 – Jusgud 2015-02-08 18:34:47

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;