2016-03-03 47 views
0
TextView textView1 = (TextView) findViewById(R.id.textView1); 
    int randomArray = (int) (Math.random() *4); 
    textView1.setText(questions[randomArray][0]); 

使用上面的代碼(使用android studio開發應用程序)我可以從我的數組中生成一個隨機問題,如下所示。從數組中生成隨機字符串,然後將其刪除,因此它不會再生

String[][] question= new String[20][5]; 

{ 
    question[0][0] = "what is my name?"; 
    question[0][1] = "Mark"; 
    question[0][2] = "Steven"; 
    question[0][3] = "Alan"; 
    question[0][4] = "Bob"; 

    question[1][0] = "what is my age?"; 
    question[1][1] = "30"; 
    question[1][2] = "31"; 
    question[1][3] = "32"; 
    question[1][4] = "33"; 
} 

下面的代碼顯示瞭如何分配答案的按鈕,這樣他們每次隨機對不同的按鈕:

Button button2 = (Button)findViewById(R.id.button2); 
    int randomArray1 = (int) (Math.random() *4); 
    button2.setText(questions[randomArray][randomArray1+1]); 

    Button button3 = (Button)findViewById(R.id.button3); 
    int randomArray2 = (int) (Math.random() *4); 
    button3.setText(questions[randomArray][randomArray2+1]); 

    Button button4 = (Button)findViewById(R.id.button4); 
    int randomArray3 = (int) (Math.random() *4); 
    button4.setText(questions[randomArray][randomArray3+1]); 

    Button button5 = (Button)findViewById(R.id.button5); 
    int randomArray4 = (int) (Math.random() *4); 
    button5.setText(questions[randomArray][randomArray4+1]); 

+1只是意味着該問題將不會被放置在按鍵。所有我需要的支援是我怎麼會去從選項中移除隨機選擇,使我沒有有2,3或4個按鈕,說史蒂夫或30等

回答

0

您可以將您的字符串的問題ArrayList,隨機化ArrayList,然後簡單地從每個按鈕的ArrayList中移除頂端條目。

mButton1.setText(mArrayList.remove(0)); 
mButton2.setText(mArrayList.remove(0)); 
+0

應該ArrayList中保持在相同的位置陣列? –

+0

我不確定我是否理解這個問題。當您想要填充按鈕,然後丟棄ArrayList會生成。你只需要跟蹤哪個答案是正確的。 – Francesc

0

如果你把你想在ArrayList顯示答案,然後你可以使用Collections.shuffle()簡單隨機的順序。然後,您只需將答案逐個放入他們的視圖中,他們就會自動爲您洗牌。通過這樣做,您不必擔心重複,因爲您只會在列表中找到每個答案的一個副本。所以這只是一個將它們逐一按照新隨機順序排列在視圖中的問題。

檢查了這一點......這裏是它的工作原理是:

ArrayList<String> answers = new ArrayList<>(); 
answers.add("dave"); 
answers.add("steve"); 
answers.add("john"); 
answers.add("carl"); 

for(int i=0; i<answers.size(); i++) { 
    //answers in their original order 
    Log.d("ANSWERS", answers.get(i)); 
} 

Collections.shuffle(answers, new Random()); 

for(int i=0; i<answers.size(); i++) { 
    //answers are now in a randomized order 
    Log.d("SHUFFLED ANSWERS", answers.get(i)); 
}