2012-02-20 72 views

回答

1

創建問題的數組:

List<String> questions = new ArrayList<String>() {{ 
    add("6 + 7 = ??"); 
    add("8 + 9 = ??"); 
    add("11 - 3 = ??"); 
}} 

然後,隨便挑之間0隨機指數和陣列的長度-1:

Random rnd = new Random(); 
String randomQuestion = questions.get(
    rnd.nextInt(questions.length) 
); 

PS該行rnd.nextInt(questions.length)的功勞歸於@WarrenFaith。我是用做的極其愚蠢的做法吧[(int)(rnd.nextFloat()*(questions.length-1))]

相反,你可能需要使用一類像字符串:

class Question { 
    String questionString; 
    int answer; 

    // .. Definitions and declarations 
} 

我會留給你高達作爲一個鍛鍊; Tibial :)

+0

'(int)(rnd.nextFloat()*(questions.length-1))'等什麼?如何更容易:'rnd.nextInt(questions.length)'? – WarrenFaith 2012-02-20 15:36:14

+0

@WarrenFaith:我目前正在思考一個很好的藉口:( – 2012-02-20 17:17:20

+0

:P不需要:) – WarrenFaith 2012-02-20 19:46:48