2017-04-03 48 views
0

我想知道如何實現我的布爾playAgain。我知道目前它沒有做任何事情,它只是無用的代碼。但我不知道如何將它變成一個讓我的遊戲再次玩的功能。我上次從來沒有得到答案。再次實施劇本布爾

System.out.println("Guess a number between 1-100."); 

    Scanner keyboard = new Scanner(System.in); 
    Random rand = new Random(); 
    int number = rand.nextInt(100)+1; 
    int round = 1; 
    int count = 0; 
    int guess = 0; 
    int win = 0; 
    int loss = 0; 
    String playAgain = ""; 

    //Code for the game itself 

do 
{ 
    while(win == 0) 
    { 
     if (count == 0) 
     { 
      System.out.println("Round " + round); 
      System.out.println("-------"); 

      System.out.println("Secret " + number); 

      System.out.print("What is your first guess? "); 
      guess = keyboard.nextInt(); 
      count++; 
     } 

     //User Guess is correct 
     if (guess == number) 
     { 
      break; 
     } 

     //Round limit reached 
     if (count == 7 && guess != number) 
     { 
      ++loss; 
      break; 
     } 

     //User Guess is too high 
     if (guess > number) 
     { 
      System.out.print("That's too high. Try again: "); 
      guess = keyboard.nextInt(); 
      count++; 
     } 

     //User Guess is too low 
     if (guess < number) 
     { 
      System.out.print("That's too low. Try again: "); 
      guess = keyboard.nextInt(); 
      count++; 
     } 
} 
     boolean isValidAnswer; 
     System.out.print("\nWould you like to play again (yes/no)? "); 
     playAgain = keyboard.next().toUpperCase(); 
     isValidAnswer= playAgain.equals("YES") || playAgain.equals("NO"); 
     if(! isValidAnswer) 
     { 
      System.out.println("Error: Please enter yes or no"); 
      System.out.println(); 
     } 
} while(playAgain.equals("YES")); 


    //If user wins 
    //Count = 1 word is guess 
    if (guess == number) 
    { 
     if (count == 1) 
     { 
      round++; 
      System.out.println("You got it in " + count + " guess."); 
      ++win; 
     } 
    } 
+0

把整個代碼在do-while循環,並循環直到用戶想玩。同樣在'isValid = playAgain.equals(「yes」)|| playAgain.equals(「是」);'一個「是」應該是「否」我想。 –

回答

0

你可以做這樣的事情:

boolean status = true; 


if(win > 0){ 

System.out.print("Would you like to play again (true/false)? "); 
System.out.println(); 
System.out.println("Error: Please enter true or false"); 
String input = scan.nextLine(); 


if(status != input){ 

// do not do anything or close the program. 
} 
else { 

// do something cause players wants to play again. 
} 
} 
0

你可以做這樣的事情......

Scanner in = new Scanner(System.in); 
String playAgain = "no"; 
do { 

    // game logic 

    System.out.println("Want to play more (yes/no) ?"); 
    playAgain = in.nextLine(); 
} while(playAgain.equals("yes") || playAgain.equals("YES")); 
+0

我這樣做,我更新了我的代碼上面沒有任何反應它只是不斷問我你想再次播放 – Ezsh

+0

可以請你看一下嗎? – Ezsh

+0

@Ezsh是否在下一場比賽中將'win'值更新爲'0'?設置'win = 0;'while while while while循環啓動遊戲循環。 ,一旦勝利變成1,它將在下一場比賽中脫離循環。 –