2015-02-08 93 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;