我正在尝试创建一个国家测验猜谜游戏但是,我遇到了一个问题。我希望有一个菜单显示一个国家,下面应该有三个首都可供选择哪一个是正确的。问题是我不希望每个国家的正确答案都处于相同的位置,换句话说,我希望替代方案的顺序是随机的,但是,我不确定如何做到这一点......
我的代码并没有走得太远,但这是我的方法:
public static void gissaStadAlt(LandStad[] list) {
for(int i = 0; i < list.length; i++) {
int rand = (int)(Math.random() * 10);
JOptionPane.showInputDialog(null, "Which of the alternatives is the capital in " + list[i].land + "?" + "\n" +
"1." + list[rand].stad + "\n" +
"2." + list[i].stad + "\n" +
"3." + list[rand].stad);
}
}
我希望list [i] .stad的位置是随机的
这是我的LandStad课程:
public class LandStad {
String land;
String stad;
}
答案 0 :(得分:1)
为什么不随便洗一下你得到的阵列?这样你就可以使JOptionPane对话保持一致,即:
public static void gissaStadAlt(LandStad[] list)
{
Collections.shuffle(Arrays.asList(list));
JOptionPane.showInputDialog(null, "Which of the alternatives is the
capital in " + list.getLand() + "?" + "\n" +
"1." + list[0].city + "\n" +
"2." + list[1].city + "\n" +
"3." + list[2].city);
}
答案 1 :(得分:0)
您可以使用以下内容:
public static void gissaStadAlt(LandStad[] list) {
for(int i = 0; i < list.length; i++) {
String[] options = new String[3];
int rand = i;
while(rand!=i){
rand = (int)(Math.random() * 10);
}
options[0] = list[rand].city;
int k = rand;
while(rand!=i && rand!=k){
rand = (int)(Math.random() * 10);
}
options[1] = list[rand].city;
options[2] = list[i].city;
int[] randomize = {123,132,213,231,312,321};
int num = randomize[(int)(Math.random() * 6)];
for(int i=0;i<3;i++){
int g = num/100;
options[i] = g + ". " + options[i];
num%=100;
num*=10;
}
Arrays.sort(options);
JOptionPane.showInputDialog(null, "Which of the alternatives is the capital in " + list[i].land + "?" + "\n" +
options[0] + "\n" +
options[1] + "\n" +
options[2]);
}