2011-11-18 21 views
0

我在這裏要做的是總是從我的字符串arraylist中獲取一個隨機值,爲此我使用另一個包含與字符串相同數量的布爾值的arraylist。爲什麼不用if語句處理我的布爾數組列表?

當我需要一個隨機字符串我這樣做:

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!!!!!!!!!!!!!!!"); 
} 

,這是它的外觀裏面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; 

但是,當我嘗試這樣做可以隨機我的字符串如何很多我想要的和它打印到控制檯的東西被設置爲true,但我看到很多次相同的字符串得到再次使用和System.out.println("Already used string random again!");永遠不會被打印在控制檯上

與我稱之爲getAnswear時相同,我有if語句(c.getAnswear(randomstring) == null)System.out.println("random again!!!!!!!");裏面的行永遠不會進入控制檯。

我該如何使它工作?好像getAnswear裏面的答案字符串從不爲空,這很奇怪,因爲我將布爾值設置爲true。

回答

3

trueornot.add(indexNum, true)
這會將值添加到列表中,並將該索引處的上一個值向下移動到列表中。

你應該使用trueornot.set(...)它取代了價值...

更新:

,這是它的外觀裏面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 

如果實際發生每次調用getAnswer時,都會重新創建字符串和布爾列表,所有以前的更改都會丟失。
stringstrueornot應該是類字段而不是局部變量。

+0

我確實使用了trueornot.set()之前,但因爲它它的發生同樣的事情不是..我只是試着用.add – Rakso

+0

請看更新 – yurib

+0

哦..這是真的,但我不能把它放在這個方法之外,我也不能在另一個方法中創建它。 – Rakso

2

可能是,你想設置你的值爲true,而不是插入它?

你這樣做:

trueornot.add(indexNum, true); 

,而是設置一個值,你必須這樣做:

trueornot.set(indexNum, true); 
+0

與我在其他answear上評論過的一樣,我之前使用了trueornot.set(),但它發生的事情與它一樣不是的..我只是試着用.add – Rakso

+0

我沒有看到答案,當我張貼我的^^ – Hachi