简体   繁体   中英

Java: Guessing game with randomized choice order

I'm trying to create a country quiz guessing game however, I have run into a problem. I want there to be a menu where a country is displayed and underneath there should be three capitals to choose from of which one is correct. The problem is I don't want the correct answer to be at the same position for every country, in other words I want the order of the alternatives to be randomized but, I'm not sure of how this could be done...

I have not come far with my code but here is my method:

  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);
  }


}

I want the position of list[i].stad to be randomized

This is my LandStad class:

public class LandStad {

    String land;
    String stad;
}

Why not just shuffle the array that you get? That way you can keep the JOptionPane dialogue the same, ie:

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);
}

You can use something like:

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]);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM