2014-02-12 58 views
3

我有一些包含字符串的數組,我想從每個數組中隨機選擇一個項目。我怎樣才能做到這一點?從java中的字符串數組中挑選一個隨機項目

這裏是我的數組:

static final String[] conjunction = {"and", "or", "but", "because"}; 

static final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"}; 

static final String[] common_noun = {"man", "woman", "fish", "elephant", "unicorn"}; 

static final String[] determiner = {"a", "the", "every", "some"}; 

static final String[] adjective = {"big", "tiny", "pretty", "bald"}; 

static final String[] intransitive_verb = {"runs", "jumps", "talks", "sleeps"}; 

static final String[] transitive_verb = {"loves", "hates", "sees", "knows", "looks for", "finds"}; 
+0

入住這http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array –

+0

非常感謝你米對你們所有人! – user3266734

回答

14

使用Random.nextInt(int)方法:

final String[] proper_noun = {"Fred", "Jane", "Richard Nixon", "Miss America"}; 
Random random = new Random(); 
int index = random.nextInt(proper_noun.length); 
System.out.println(proper_noun[index]); 

此代碼是不是完全安全的:一個超時四個它會選擇理查德·尼克松。

引述一個文檔Random.nextInt(int)

返回之間0 (含)的僞隨機均勻分佈的int值和傳遞數組長度的指定值(不)

在你的情況到nextInt將做的伎倆 - 你會得到範圍內的隨機數組索引[0; your_array.length)

0

如果你想循環你的數組,你應該把它們放入一個數組中。否則,你需要分別爲每個選擇一個隨機選擇。

// I will use a list for the example 
List<String[]> arrayList = new ArrayList<>(); 
arrayList.add(conjunction); 
arrayList.add(proper_noun); 
arrayList.add(common_noun); 
// and so on.. 

// then for each of the arrays do something (pick a random element from it) 
Random random = new Random(); 
for(Array[] currentArray : arrayList){ 
    String chosenString = currentArray[random.nextInt(currentArray.lenght)]; 
    System.out.println(chosenString); 
} 
1

如果使用List代替陣列,您可以創建簡單的通用方法,讓你從任何列表中隨機元素:

public static <T> T getRandom(List<T> list) 
{ 
Random random = new Random(); 
return list.get(random.nextInt(list.size())); 
} 

,如果你想留在陣列,你仍然可以有你的通用方法,但它會看起來有點不同

public static <T> T getRandom(T[] list) 
{ 
    Random random = new Random(); 
    return list[random.nextInt(list.length)]; 

}