2013-11-24 47 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

相关问题