gpt4 book ai didi

java - 在Java中,如何使数组中的每个元素成为一个按钮?

转载 作者:行者123 更新时间:2023-11-29 08:56:13 25 4
gpt4 key购买 nike

对于我的 CS 项目,我正在做一个多项选择测验。每个测验都有一个问题和四个可能的答案。正确答案保存为字符串。所有错误的答案都保存在一个字符串数组中。我想为每个按钮制作一个按钮。但是我不想让正确答案一直在同一个位置,所以我想随机放置。乱放之后不知道怎么给字符串数组做按钮。帮助!

` 公共(public)显示(){

    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

}
}`

最佳答案

编辑

现在回答你的问题:

因为您事先知道有多少个按钮,您可以简单地使用一个数组。

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.

希望这对您有所帮助。

关于java - 在Java中,如何使数组中的每个元素成为一个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com