I'm currently trying to create a randomly generated string. Problem is, with the way I have it setup it continues to add on to itself.
My code ( I'm calling a lot of static variables from another class so don't worry about that portion)
class Generate1 extends Thread{
@Override
public void run() {
while(RUNNING == true){
generate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void generate(){
for(int i=0;i<length;i++){
int decider = rando.nextInt(6)+1;
if(decider == 1){
sb1.append("A");
}
if(decider == 2){
sb1.append("B");
}
if(decider == 3){
sb1.append("C");
}
if(decider == 4){
sb1.append("D");
}
if(decider == 5){
sb1.append("E");
}
if(decider == 6){
sb1.append("F");
}
}
Log.d("PSS",sb1.toString()); // this here is the stringbuilder being outputted
}
}
if I set length to 2, in my log it would look something like:
DF DFCA DFCAEF
instead of my desired output:
DF CA EF
how do I fix this? ( I know this is probably a stupid question but it's late and pondering through code hurts my eyes and brain )
edit - shmosel brought light to what was wrong. It was a really simple fix to me overlooking something
You're using the same
StringBuilder
instance for each call togenerate()
. Use a fresh one instead: