2015-05-27 3 views
-1

Так что я делаю Кто хочет стать миллионером, и у меня все работает отлично. Но иногда вопросы повторяются, и это не делает хорошей игры, если вы дважды получаете тот же вопрос. Я был бы признателен всем и любой помощи.Как сделать Вопросы не повторяться

import java.io.*; 
import java.util.*; 
public class MillionaireGame { 


    public static void main(String[] args) { 


     // gets the users name 
     Scanner kbreader = new Scanner(System.in); 
     System.out.println("Hello welcome to Wants to Be A Millionaire, Can i get your name please."); 
     String name; 
     name=kbreader.next(); 

     // introduce the host and have the host explain the rules 
     System.out.println("Welcome again " + name +" I am your host Antonio. i'll be here with you while you play."); 
     System.out.println("I am here to explain the rules to you and be a host. let me tell you the rules of the game."); 
     System.out.println("We will ask you a series of questions 14 in total and you win money if you get the questions right"); 
     System.out.println("There two check points $10000 and $320000. if you lose or quit before $10000 you go home empty handed."); 
     System.out.println("If you lose or quit after the $10000 question but before the $320000 you go home with $10000."); 
     System.out.println("If you lose or quit after the $320000 question but before the $1000000 you go home with $320000."); 
     System.out.println("Let the games being computer first question please."); 

     //The string array is to how the possible question one 
     String question1[]={"What year did world war 2 end in", 
       "The canadian great depression started in", 
       "Sir John A Mcdonald last term started in", 
       "Canada became its own contruy in",}; 

     //these string arrays are to keep the asnswer for the questions and give the other options 
     String answer1[]={"1945","1929","1891","1867",}; 
     String options1[]={"1943","1904","1886","1782","1748","1764","1897","1823","1899","1858","1900","1909",}; 

     String question2[]={"What is the capital of Yukon", 
       "What is the capital of Northwest Territories", 
       "Where is Parliament Hill", 
       "_________ is called No Fun City "}; 

     String answer2[]={"Whitehorse","Yellowknife","Ottawa","Vancouver"}; 
     String options2[]={"London","Kingston","Saint John","Winnipeg","Victoria","Edmonton","Calgary","Montreal"}; 

     //The string array is to how the possible question one 
     String question3[]={"Which country has the most people", 
       "Which country invented football(soccer)", 
       "Which country started World War one", 
       "Which country has the largest debt",}; 

     //these string arrays are to keep the asnswer for the questions and give the other options 
     String answer3[]={"China","England","Austria-Hungary","United States",}; 
     String options3[]={"Canada","India","Japan","Germany","Russia","Brazil","France","Mexio","Egypt","Jamaica","Italy","Austria",}; 

     //The string array is to how the possible question one 
     String question4[]={"To which Super-Hero was With great power comes Great Responsibility said to", 
       "Which Super-Hero takes the role of Captain America after he died", 
       "What is the name of the Acher on the Avengers", 
       "Other than Captian America, Chris Evans acted as which Super-Hero",}; 

     //these string arrays are to keep the asnswer for the questions and give the other options 
     String answer4[]={"Spider-Man","Winter Soldier","Hawkeye","Human Torch",}; 
     String options4[]={"Super-Man","Batman","Flash","Iron Man","Hulk","Thor","DareDevil","Green Arrow","QuickSliver","Super-Girl","Nova","StarLord",}; 

     //This int array is to hold the prices for the money and keep count of it as the play gets higher 
     int money[]={0,1000,2000,3000,5000,10000,20000,40000,80000,160000,320000,640000,1250000,2500000,5000000,10000000}; 

     //This string array is to talk to the user and give them the next question 
     String com1[]={"Antonio: Coumpter what is next question", 
       "Antonio: Next question please", 
       "Antonio: Are you ready for the next question", 
       "Antonio : Next question Please"}; 

     String com2[]={"Antonio: We will tell you what the answer was", 
       "Antonio: Since you quit you get to know the answer", 
       "Antonio: Since you're dying to know what the answer was", 
       "Antonio: The computer will show you the answer"}; 

     //this random is to get pick which questions answers and options are printed 
     Random r= new Random(); 
     int qch,ra,rq=0,ans=0,nextq=0,m=1,bal=0; 
     do{ 
     System.out.println("\033"); 
     qch=r.nextInt(4); 
     int len1=options1.length; 
     int len2=options2.length; 
     int len3=options3.length; 
     int len4=options4.length; 
     System.out.println("\nyou have won= "+money[bal]+"\n"); 
     System.out.println("\n\tThis question is for $"+money[m]+"\n");   

     //if statements to matcht he answer with the question even after it was randomize 
     //the if statements also print out the options 
     if(qch==0) 
     { 
      rq=r.nextInt(4); 
      System.out.println(question1[rq]); 
      ra=r.nextInt(4); 
      if(ra==0) 
      { 
       System.out.println(answer1[rq]); 
       for(int i=0;i<3;i++) 
       System.out.println(options1[r.nextInt(len1)]); 
       ans=1; 
      } 
      if(ra==1) 
      { 
       System.out.println(options1[r.nextInt(len1)]); 
       System.out.println(answer1[rq]); 
       for(int i=0;i<2;i++) 
       System.out.println(options1[r.nextInt(len1)]); 
       ans=2; 
      } 
      if(ra==2) 
      { 
       for(int i=0;i<2;i++) 
       System.out.println(options1[r.nextInt(len1)]); 
       System.out.println(answer1[rq]); 
       System.out.println(options1[r.nextInt(len1)]); 
       ans=3; 
      } 
      if(ra==3) 
      { 
       for(int i=0;i<3;i++) 
       System.out.println(options1[r.nextInt(len1)]); 
       System.out.println(answer1[rq]); 
       ans=4; 
      } 

     } 
     if(qch==1) 
     { 
      rq=r.nextInt(4); 
      System.out.println(question2[rq]); 
      ra=r.nextInt(4); 
      if(ra==0) 
      { 
       System.out.println(answer2[rq]); 
       for(int i=0;i<3;i++) 
       System.out.println(options2[r.nextInt(len2)]); 
       ans=1; 
      } 
      if(ra==1) 
      { 
       System.out.println(options2[r.nextInt(len2)]); 
       System.out.println(answer2[rq]); 
       for(int i=0;i<2;i++) 
       System.out.println(options2[r.nextInt(len2)]); 
       ans=2; 
      } 
      if(ra==2) 
      { 
       for(int i=0;i<2;i++) 
       System.out.println(options2[r.nextInt(len2)]); 
       System.out.println(answer2[rq]); 
       System.out.println(options2[r.nextInt(len2)]); 
       ans=3; 
      } 
      if(ra==3) 
      { 
       for(int i=0;i<3;i++) 
       System.out.println(options2[r.nextInt(len2)]); 
       System.out.println(answer2[rq]); 
       ans=4; 
      } 

     } 
     if(qch==2) 
     { 
      rq=r.nextInt(4); 
      System.out.println(question3[rq]); 
      ra=r.nextInt(4); 
      if(ra==0) 
      { 
       System.out.println(answer3[rq]); 
       for(int i=0;i<3;i++) 
       System.out.println(options3[r.nextInt(len3)]); 
       ans=1; 
      } 
      if(ra==1) 
      { 
       System.out.println(options3[r.nextInt(len3)]); 
       System.out.println(answer3[rq]); 
       for(int i=0;i<2;i++) 
       System.out.println(options3[r.nextInt(len3)]); 
       ans=2; 
      } 
      if(ra==2) 
      { 
       for(int i=0;i<2;i++) 
       System.out.println(options3[r.nextInt(len3)]); 
       System.out.println(answer3[rq]); 
       System.out.println(options3[r.nextInt(len3)]); 
       ans=3; 
      } 
      if(ra==3) 
      { 
       for(int i=0;i<3;i++) 
       System.out.println(options3[r.nextInt(len3)]); 
       System.out.println(answer3[rq]); 
       ans=4; 
      } 

     } 
     if(qch==3) 
     { 
      rq=r.nextInt(4); 
      System.out.println(question4[rq]); 
      ra=r.nextInt(4); 
      if(ra==0) 
      { 
       System.out.println(answer4[rq]); 
       for(int i=0;i<3;i++) 
       System.out.println(options4[r.nextInt(len4)]); 
       ans=1; 
      } 
      if(ra==1) 
      { 
       System.out.println(options4[r.nextInt(len4)]); 
       System.out.println(answer4[rq]); 
       for(int i=0;i<2;i++) 
       System.out.println(options4[r.nextInt(len4)]); 
       ans=2; 
      } 
      if(ra==2) 
      { 
       for(int i=0;i<2;i++) 
       System.out.println(options4[r.nextInt(len4)]); 
       System.out.println(answer4[rq]); 
       System.out.println(options4[r.nextInt(len4)]); 
       ans=3; 
      } 
      if(ra==3) 
      { 
       for(int i=0;i<3;i++) 
       System.out.println(options4[r.nextInt(len4)]); 
       System.out.println(answer4[rq]); 
       ans=4; 
      } 

     } 


     //The Scanner to get input from the user 
     //Made a second scanner to save as the answer from the user 
     Scanner sc=new Scanner(System.in); 
     int uans; 
     System.out.println("\n\t\tenter your answer 1,2,3,4"); 
     System.out.println("\n\t\tif you want to quit enter 5"); 
     uans=sc.nextInt(); 
     if(uans==ans) 
     { 
      System.out.println("\n\t\t\tCorrect answer\n"); 
      nextq=1;m++;bal++; 

      //if they won the whole game this is printed out 
      if(m==14) 
      { 
       System.out.println("\nCongrats\t\tCongrats"); 
       System.out.println("\n\t\t You Won A $" + m); 
       System.out.println("\nCongrats\t\tCongrats"); 
      } 
     } 

     // if the user chose to quit the game this is printed 
     else if(uans==5) 
     { 
      System.out.println("\t\t\tYou have chose to quit the game"); 
      System.out.println(com2[r.nextInt(4)]); 
      System.out.print("\t\tThe answer to the question was "); 
      if(qch==0) 
       System.out.println("option "+ans+" "+answer1[rq]); 
      if(qch==1) 
       System.out.println("option "+ans+" "+answer2[rq]); 
      if(qch==2) 
       System.out.println("option "+ans+" "+answer3[rq]); 
      nextq=0; 
      if(qch==3) 
       System.out.println("option "+ans+" "+answer4[rq]); 
      nextq=0; 
     } 

     //if the user chose the wrong answer to the Question this is printed 
     else 
     { 
      nextq=0; 
      System.out.println("\n\t Sorry that is the wrong answer"); 
      System.out.print("\t\tThe answer to the question was "); 
      if(qch==0) 
       System.out.println("option "+ans+" "+answer1[rq]); 
      if(qch==1) 
       System.out.println("option "+ans+" "+answer2[rq]); 
      if(qch==2) 
       System.out.println("option "+ans+" "+answer3[rq]); 
      nextq=0; 
      if(qch==3) 
       System.out.println("option "+ans+" "+answer4[rq]); 
      nextq=0; 
      System.out.print("\t\t\t You have won $"); 

      //Checks how much money the user already has then prints out how much they won 
      if((money[bal]<10000)&&(money[bal]>=0)) 
      System.out.println("0"); 
      if((money[bal]<320000)&&(money[bal]>=10000)) 
      System.out.println("10000"); 
      if((money[bal]<10000000)&&(money[bal]>=320000)) 
      System.out.println("320000"); 
     } 
     if(nextq==1) 
      System.out.println(com1[r.nextInt(4)]); 
     }while(nextq==1); 
    } 

} 
+1

следует хранить задаваемый вопросы в различных структурах данных (массив) и убедитесь, что ваше случайное число не в этом. –

+0

Кроме того, у вас есть опечатка здесь: «Пусть игры будут компьютерным, первый вопрос пожалуйста.»;) – CubeJockey

+0

Спасибо, что указали, что вне –

ответ

1

Одним из вариантов такого рода вещи, чтобы создать List, содержащие все ваши вопросы, случайно перемешать его с помощью Collections.shuffle(), а затем создать из него очереди. Затем вы можете просто вызывать вопросы с вашей очереди, и вы никогда не будете повторять вопрос. Вероятно, проще, чем отслеживать, какие вопросы были заданы.

Вот пример того, делать это с помощью простого списка целых чисел:

package test; 

import java.util.ArrayDeque; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.List; 
import java.util.Queue; 



public class Test { 

    public static void main(String[] argv) { 
    List<Integer> intList = Arrays.asList(1,2,3,4,5); 
    Collections.shuffle(intList); 
    Queue<Integer> intQueue = new ArrayDeque<Integer>(intList); 
    Integer x; 
    while ((x = intQueue.poll()) != null) { 
     System.out.println(x); 
    } 
    } 

} 
+0

1 up for Collections.shuffle() точно, что я пытаюсь сделать – gifpif

+0

Спасибо, что все вышло в конце –

0

отслеживать, какие вопросы были заданы уже в ArrayList (в качестве альтернативы, вы можете использовать любой вид способа хранения доступны для вас), и проверить, что список, чтобы увидеть, если вопрос, который вы собираетесь спросить был задан раньше. Если да, задайте другой вопрос. В противном случае задайте вопрос.


Я не собираюсь отлаживать этот массивный свалку кода для вас, и я сомневаюсь, что многие из нас будут. Пожалуйста, прочитайте How to Ask, чтобы улучшить ваши шансы на лучший ответ.

+0

Альтернативно OP может хранить ответы в 'ArrayList' для начала и просто удалять вопросы, поскольку они - спросил он. Хотя похоже, что это может быть назначение курса начального уровня без введения в «ArrayList» – CubeJockey

+0

@Trobbins. Именно потому, что это похоже на назначение курса, и что это всего лишь дамп кода, я только предоставил возможную возможность вместо фактического кода. – Aify

0

Не используйте случайное число в то время, когда задан первый вопрос. Создает список случайных чисел, в которые задаются вопросы, прежде чем задавать любые вопросы.

Используйте LinkedHashSet, который поддерживает случайную последовательность и уникальность.

Set<Integer> generated = new 
LinkedHashSet<Integer>(); 
while (generated.size() < numbersNeeded) 
    { 
     Integer next = rng.nextInt(max) + 1; 
     generated.add(next); 
    } 

 Смежные вопросы

  • Нет связанных вопросов^_^