User
User

Reputation: 1488

Why don't if statements work with my boolean arraylist?

What I'm trying to do here is to always get a random value from my String arraylist and to do this I'm using another arraylist containing the same amount of booleans as the strings.

When I need a random string I do this:

randomstring = r.nextInt(100);
String mystring = c.getAnswear(randomstring);

if(c.getAnswear(randomstring) == null){
    randomstring = r.nextInt(100);
    mystring = c.getAnswear(randomstring);
    System.out.println("Random again!!!!!!!!!!!!!!!");
}

And this is how it looks inside c.getAnswear

List<String> strings = new ArrayList<String>();
strings.add("blablabla");
//And another 100 of theese
//Then we have theese boolean array
ArrayList<Boolean> trueornot = new ArrayList<Boolean>();
trueornot.add(false);
//Another 100 of them
//Then we have this
String Answear = null;
if(trueornot.get(indexNum).equals(true)){
   Answear = null;
   System.out.println(Answear);
   System.out.println("Already used string random again!");
}
else if(trueornot.get(indexNum).equals(false)){
    trueornot.add(indexNum, true);
    Answear = strings.get(indexNum);
    System.out.println(Answear);
    System.out.println("Something in the array was set to true");
}
return Answear;

But when I try to do this can randomize my string how much I want and it prints to console something was set to true but I see many times the same string gets used again and the System.out.println("Already used string random again!"); never gets printed in the console

Same with when I call this getAnswear I have the if statement (c.getAnswear(randomstring) == null) the line inside there System.out.println("random again!!!!!!!"); never gets into the console.

How would I make it work? Seems like the answer string inside getAnswear is never null and that's strange because I'm setting the booleans to true.

Upvotes: 0

Views: 1569

Answers (2)

yurib
yurib

Reputation: 8147

trueornot.add(indexNum, true)
this adds the value to the list and shifts the previous value at that index down the list.

you should use trueornot.set(...) which replaces the value...

update:

And this is how it looks inside c.getAnswear

List<String> strings = new ArrayList<String>();

strings.add("blablabla");

//And another 100 of theese
//Then we have theese boolean array

ArrayList<Boolean> trueornot = new ArrayList<Boolean>();

trueornot.add(false);

//Another 100 of them
//Then we have this

if this actually happens every time getAnswer is called then you're recreating the strings and the boolean list everytime, all previous changes are lost.
strings and trueornot should be class fields and not local variables.

Upvotes: 3

Hachi
Hachi

Reputation: 3289

may it be, you want to set your value true, instead of insert it?

you do this:

trueornot.add(indexNum, true);

but to set a value you have to do this:

trueornot.set(indexNum, true);

Upvotes: 2

Related Questions