2015-10-04 2 views
0

Я делаю программу, которая по сути является викториной фильма, читая названия фильмов/даты выпуска/жанр/грубые данные из текстового файла, который я получил нормально, проблема в том, что это делает цикл while, чтобы работать правильно путем отказа в любое время, когда пользователь вводит нет, когда будет предложено в оба раза (после каждого вопроса и в самом конце) Любые советы/советы приветствуются!Делать пока петли? (JAVA)

Вот что у меня есть:

private static void movieQuiz (Movies[] movieRecord){ 

    int score = 0; 
    Scanner keyboard = new Scanner (System.in); 
    String userChoice; 

    System.out.println("You have selected the Movie Quiz! The instructions" 
      + " are as follows: The program will output \nthe title of one of " 
      + "the highest grossing films of all time, your job is " 
      + "to guess which year \nit was released. A point will be added " 
      + "to your score for each correct answer, and your total \npoints will" 
      + " display at the end or until you want to give up. Have fun and" 
      + " good luck!\n"); 
    int test = 0; 
    loadMovies(movieRecord); 
    System.out.println("Are you ready to begin?"); 
    userChoice = keyboard.next(); 

    //do this if they want to run it again 
    do { 
     for (int count = 0; count <= movieRecord.length-1; count++) { 
     System.out.println("Movie #" + (test+1) + ": " + movieRecord[count].movieTitle); 
     System.out.println("Guess the year"); 
     int guess = keyboard.nextInt(); 

      if (guess == movieRecord[count].releaseYear){ 
      System.out.println("DING DING DING! (+1) \n"); 
      score++; 
      } 

      else { 
      System.out.println("Wrong (+0) \n"); 
      } 

      System.out.println("Continue? (Currently on #" + (1 + test) + " out of " 
      + movieRecord.length + ")"); 
      userChoice = keyboard.next(); 

      test++; 

     } 
    } while (userChoice.charAt(0) == 'y'); 

     //display if they type 'no' at any time, ending the program 
     System.out.println("Total Score is: " + score + " out of " + movieRecord.length); 
     System.out.println("AGAIN? yes/no?"); 
     userChoice = keyboard.next(); 
} 

ответ

0

Возьмите break !!!!

Вам нужно узнать о перерыве в Java и реализовать его в своем коде.

+0

Не поймите меня неправильно, я полностью осведомлен о заявлении разрыва, но по той причине, что в настоящее время отводящего меня, мой профессор предупреждал нас, используя заявления перерыва в целом и попытаться найти другие альтернативы. Независимо от того, я получил его на работу, спасибо вам всем – cbsack

0

Не могли бы вы попробовать это?

 int score = 0; 
     Scanner keyboard = new Scanner (System.in); 
     String userChoice; 

     System.out.println("You have selected the Movie Quiz! The instructions" 
       + " are as follows: The program will output \nthe title of one of " 
       + "the highest grossing films of all time, your job is " 
       + "to guess which year \nit was released. A point will be added " 
       + "to your score for each correct answer, and your total \npoints will" 
       + " display at the end or until you want to give up. Have fun and" 
       + " good luck!\n"); 
     int test = 0; 
     loadMovies(movieRecord); 
     System.out.println("Are you ready to begin?"); 
     userChoice = keyboard.next(); 

     //do this if they want to run it again 
     do { 
      for (int count = 0; count <= movieRecord.length-1; count++) { 
      System.out.println("Movie #" + (test+1) + ": " + movieRecord[count].movieTitle); 
      System.out.println("Guess the year"); 
      int guess = keyboard.nextInt(); 

       if (guess == movieRecord[count].releaseYear){ 
       System.out.println("DING DING DING! (+1) \n"); 
       score++; 
       } 

       else { 
       System.out.println("Wrong (+0) \n"); 
       } 

       System.out.println("Continue? (Currently on #" + (1 + test) + " out of " 
       + movieRecord.length + ")"); 
       userChoice = keyboard.next(); 

       if(userChoice.charAt(0) == 'n'){ 
       //display if they type 'no' at any time, ending the program 
       System.out.println("Total Score is: " + score + " out of " + movieRecord.length); 
       System.out.println("AGAIN? yes/no?"); 
       userChoice = keyboard.next(); 
       if (userChoice.charAt(0) == 'n') 
        break; 
       } 

       test++; 

      } 
     } while (userChoice.charAt(0) == 'y'); 

    } 
+0

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

+0

На самом деле я разместил последние несколько операторов внутри цикла while (ближе к концу) и добавил разрыв, если пользователь решил окончательно остановить выполнение. Эти инструкции выполняются только в том случае, если пользователь сначала попросит покинуть игру после вопроса. –

+0

Постарайтесь это в главном: Сканер k = новый сканер (System.in); String u; System.out.println («ready?»); u = k.next(); do { for (int count = 0; count <= 5; count ++) { System.out.println ("gess number"); k.nextInt(); System.out.println («Продолжить?»); u = k.next(); if (u.charAt (0) == 'n') { System.out.println ("AGAIN? Yes/no?"); u = k.next(); if (u.charAt (0) == 'n') break; } } } while (u.charAt (0) == 'y'); } –

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