java - Returning a toString from a StringBuffer -
this 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]+"] "); 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 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 , item = item1[1] -- * beta[1] charlie[2] -- when run code second time *[1] * charlie[2] -- when run code third time *[1] *[1] charlie[2]
is possible make following?
when status = 1 , item = item1[1] -- * beta[1] charlie[2] -- when run code second time * * charlie[2] -- when run code third time * * *
this need happen in random order.
an implementation of tostring()
returned different strings randomly not match declared semantics. javadoc object.tostring()
says:
in general, tostring method returns string "textually represents" object. result should concise informative representation easy person read.
if want randomly display different parts or aspects of object, should call method different.
indeed, should consider factoring randomization out of 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] (int = 0; < nosparts; i++) { string str = yc.getpartasstring(perm[i]); ... }
this approach has advantage class easier test, more reusable, , doesn't have burden of remembering happened in previous calls string rendering method.
Comments
Post a Comment