2015-06-21 26 views
1

我試圖將jTextField的文本設置爲隨機選擇的數組列表「sQuestions」隨機部分是完整的,因爲它需要與設置對應文字,我想它會像questions.setText(sQuestions[n])類似的東西,但我不得不添加.toString()部分,現在我不知道如何調用sQuestions的具體部分,而不是整個數組出現。將文本設置爲數組列表的特定部分

Random randNum = new Random(); 
    if("science".equals(Choice)){ 
     int n = randNum.nextInt(sAnswers.size()); 
    } 
ArrayList<String> sQuestions = new ArrayList<>(); 
questions.setText(sQuestions.toString()); 
+0

實際上你的問題是什麼?請更清楚你對答案的期望。 – pnadczuk

+0

也把你的代碼的隨機部分。有了這個,就不可能知道問題是什麼。 –

回答

0

我已經閱讀4次,但我最好的猜測,你想是這樣的:

Random r = new Random(); 
int randIndex = r.nextInt(sQuestions.size()); 

questions.setText(sQuestions.get(randIndex).toString()); 

如果你有一個字符串的ArrayList,我懷疑你這樣做,你可以把toString()部分留出。

+0

我最初的.toString()部分被遺漏了,但它讓我添加它。但我會嘗試.get(randIndex) – Tristan

+0

這是因爲JTextField的setText方法需要一個字符串作爲輸入,而不是一個ArrayList的字符串=) –

+0

非常感謝! – Tristan

0

你可以使用Random#nextInt(int)選擇列表上的隨機指數:

Random r = new Random(); 
int radnomIndex = r.nextInt(sQuestions.size()); 
sQuestions.get(randomIndex).setText("some text"); 
相關問題