开发者

Returning a toString from a StringBuffer

This is my class:

    public String toString(){
    status = status1.getStat();
    item = status1.getItem();
    boolean checked;
    checked = false;
    StringBuffer sb1 = new StringBuffer("");
    StringBuffer s1, s2, s3, z;
    s1 = new StringBuffer(item1[1]+"["+item2[1]+"] ");
    s2 = new StringBuffer(item1[2]+"["+item2[2]+"] "开发者_C百科);
    s3 = new StringBuffer(item1[3]+"["+item2[3]+"] ");
    z = new StringBuffer(" player("+player+") - "+points+" points ");
    //sb1.append(item1[1]+"["+item2[1]+"] "+item1[2]+"["+item2[2]+"] "+ item1[3]+"["+item2[3]+"] "+ "player("+player+") - "+points+" points ");

    if (status == 1 && item.equals(item1[1])){
        item1[1] = "*"; 
        s1 = sb1.append(item1[1]+" ");
        //sb1.delete(1,4);
    }else if (status == 1 && item.equals(item1[2])){
        item1[2] = "*";
        s2 = sb1.append(item1[2]+" ");

    }else if(status == 1 && item.equals(item1[3])){
        item1[3] = "*";
        s3 = sb1.append(item1[3]+" ");

    }  

    return s1.toString()+s2.toString()+s3.toString()+z.toString();

My output is the following:

Let: 
 item1[1] = Alpha
 item2[1] = 1
 item3[1] = 0
 -----
 item1[2] = Beta
 item2[2] = 1
 item2[2] = 0
 -----
 item1[3] = Charlie
 item2[3] = 2

My output is:

when status = 1 and item = item1[1]
--
* Beta[1] Charlie[2]
--
When run the code for the second time
*[1] * Charlie[2]
--
When i run the code for the third time
*[1] *[1] Charlie[2]

Is it possible to make it like the following?

when status = 1 and item = item1[1]
--
* Beta[1] Charlie[2]
--
When run the code for the second time
*  * Charlie[2]
--
When i run the code for the third time
* * *

This will need to happen in random order.


An implementation of toString() that returned different strings randomly does not match the declared semantics. The javadoc for Object.toString() says:

In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read.

If you want to randomly display different parts or aspects of an object, you should call the method something different.

Indeed, you should consider factoring the randomization out of the class entirely; e.g.

    Random r = ...
    ...
    YourClass yc = ...
    int nosParts = yc.getNosParts();
    int partNo = r.nextInt(nosParts);
    String str = yc.getPartAsString(partNo);

or

    int[] perm = ... // randomly permuted array of [0 .. nosParts - 1]
    for (int i = 0; i < nosParts; i++) {
        String str = yc.getPartAsString(perm[i]);
        ...
    }

This approach has the advantage that your class is easier to test, is more reusable, and doesn't have the burden of remembering what happened in previous calls to the String rendering method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜