2011-02-13 58 views
1

我正在使用隨機數生成器從Android字符串數組中選擇一個項目。有沒有辦法將我的整數設置爲數組的長度而不實際計算數組中的項數?使用字符串數組列表長度作爲整數

下面是我使用的隨機數的代碼的一個例子:

private Random random = new Random(); 
private int n = random.nextInt(4); 

private String randText; 

public Object(Context contex) 
{ 
String[] string = context.getResources().getStringArray(R.array.text); 

randText = "Stuff to display " + string[n] +"."; 
} 

public String getRandText 
{ 
return randText 
} 

我想限定「4」作爲上述的特定數組列表的長度。任何人都知道嗎?

回答

2

我想限定「4」作爲上述的特定數組列表的長度。

也許這就是你追求的:

String[] strs = { "str1", "str2", "str3", "str4", "str5" }; 

// Select a random (valid) index of the array strs 
Random rnd = new Random(); 
int index = rnd.nextInt(strs.length); 

// Print the randomly selected string 
System.out.println(strs[index]); 

訪問實際的陣列,請執行以下操作:

Resources res = getResources(); 
String[] yourStrings = res.getStringArray(R.array.your_array); 

(然後拿到元素的數量該陣列,你做yourStrings.length。)


關於你的編輯。試試這個:

private Random random = new Random(); 
private int n; // Can't decide up here, since array is not declared/initialized 

private String randText; 

public YourObject(Context contex) { 
    String[] string = context.getResources().getStringArray(R.array.text); 
    n = random.nextInt(string.length);  // <--- Do it here instead. 
    randText = "Stuff to display " + string[n] +"."; 
} 

public String getRandText { 
    return randText; 
} 
+0

我在這裏專門討論Android,所以我在strings.xml中有一個字符串數組,我正在訪問......我沒有在我的代碼中聲明數組,只是訪問Android資源 - 所以我尋找訪問該資源的語法(strings.xml中的字符串數組)。 – thefish7 2011-02-13 21:26:00

2
List myList = ... 
int n = select.nextInt(myList.size()); 
+0

我在這裏專門討論Android,所以我有一個string.xml中的字符串數組,我正在訪問......我沒有在我的代碼中聲明數組列表,只是訪問Android資源 - 所以我正在尋找語法來訪問該資源。 – thefish7 2011-02-13 21:24:36

相關問題