2013-11-24 50 views
2

對於我的CS項目,我正在做一個多選題測驗。每個測驗都有一個問題和四個可能的答案。正確的答案被保存爲一個字符串。所有錯誤的答案都保存在一個字符串數組中。我想爲每個人製作一個按鈕。但我不希望正確的答案始終處於相同的位置,所以我想隨機放置它。在我隨機放置它之後,我不知道如何爲字符串數組製作按鈕。幫幫我!在Java中,如何使數組中的每個元素成爲一個按鈕?

` 公共顯示器(){

answer1 = new JButton("1"); 
    answer2 = new JButton("2"); 
    answer3 = new JButton("3"); 
    answer4 = new JButton(""); 
    question = new JLabel ("question?"); 
} 

public Display(String question1, String [] answers, String correct, String pictureName){ 
    //create a panel to hold buttons 

    SimplePicture background = new SimplePicture(pictureName); 
    JLabel picture = background.getJLabel(); 

    question = new JLabel(question1); 

    //assign answers to buttons 

    //generate a random number to determine where correct goes 
    int index = (int)(Math.random()*4); 

    //place correct answer in a certain button 
    if (index == 0){ 
     answer1 = new JButton(correct); 
    } 
    else if (index == 1){ 
     answer2 = new JButton(correct); 
    } 
    else if (index == 2){ 
     answer3 = new JButton(correct); 
    } 
    else if (index == 3){ 
     answer4 = new JButton(correct); 
    } 

    //fill other spots with answers 
    for (int i=0; i < answers.length; i++){ 
     this is where I need help 

     } 
    }` 
+0

也許某種形式的視覺會有幫助。我不理解你想要的結果。 –

回答

0

編輯現在

與回答你的問題:

既然你事先知道有多少按鈕有,你可以簡單地使用數組。

JButton[] buttons; 

buttons = new JButton[4] // or new JButton[answers.length] if you ever 
         // want to increase the amount of answers. 

//assign answers to buttons 

//generate a random number to determine where correct goes 
int index = (int)(Math.random() * 4); 

//put the correct answer to the random button: 
buttons[index] = new JButton(correct) 

//fill other spots with answers 
for (int i = 1; i <= answers.length; i++) { 
    buttons[(index + i) % answers.length] = new JButton(answers[i - 1]); 
} 

那麼這樣做的情況下,你不知道的%是Java中的模運算。所以如果(index + i)曾經超過3(假設answers.length是3)它將會再次變爲0,所以你不會得到IndexOutOfBoundsException

希望這會有所幫助。

+0

我收到帶有列表的錯誤消息。它說List不是泛型的,它不能用參數進行參數化。我該怎麼辦? – darknessofshadows

+0

嗯,確保你有正確的進口:我會將它們添加到上面的答案 – Octoshape

+0

@darknessofshadows你做了那個工作? – Octoshape

相關問題