2013-11-20 132 views
5

我想寫一個小遊戲,但一直堅持如何提示用戶,如果他們想再次玩以及如何退出循環,如果他們不想再玩。 ..如何退出Java循環? While循環在基本的猜謎遊戲

import java.util.Random; 
import java.util.Scanner; 

public class Guessinggame { 

public static void main(String[] args) { 

    System.out.println("Welcome to guessing game! \n" + " You must guess a number between 1 and 100. "); 

    while (true) { 

     Random randomNumber = new Random(); 
     Scanner g = new Scanner(System.in); 

     int number = randomNumber.nextInt(100) + 1; 
     int guess = 0; 
     int numberOfGuesses = 0; 

     while (guess != number){ 

      System.out.print("Guess: "); 
      guess = g.nextInt(); 

      if (guess > number){ 
       System.out.println("You guessed too high!"); 
      }else if (guess < number){ 
       System.out.println("You guessed too low!"); 
      }else{ 
       System.out.println("Correct! You have guessed "+ numberOfGuesses + " times. \nDo you want to play again? (y/n) "); 

      } 
      numberOfGuesses++; 


     } 
    } 
} 

}

+0

退出循環的最佳選擇是使用'break'。因此,創建一個條件(如果)並檢查用戶是否想再次播放,如果不是,則返回中斷 – k4sia

回答

11

您可以使用break走出電流回路。

for (int i = 0; i < 10; i++) { 
    if (i > 5) { 
    break; 
    } 
    System.out.Println(i); 
} 

打印:

0 
1 
2 
3 
4 
5 

然而,do-while循環可能是您的使用情況較好。

5

變化

while(true){ 
    //At some point you'll need to 
    //exit the loop by calling the `break` key word 
    //for example: 

    if(/*it's not compatible with your condition*/) 
    break; 
} 

boolean userWantsToPlay=true; 
do{ 
    //the same as before 
} while (userWantsToPlay); 

某處,然後詢問用戶是否仍然要玩,如果沒有這個變量設置爲false

另一種解決方案是讓你的代碼保持原樣,然後在詢問用戶並且他們說他們不想繼續下去之後調用break;,這只是跳出當前循環並在第一個點後恢復循環。 這不是首選,因爲在讀取代碼時跟蹤程序流程會更困難,尤其是當您開始有嵌套循環或多個點時。

0

您可以用do while聲明更改while(true)聲明。

Scanner k= new Scanner(System.in); 

do{ 
// do sth here... 

//ask to user for continue or exit 
System.out.println("Continue/Break"); 
String answer = k.next(); 

}while(answer.equals("Continue")); 

如果你想退出循環,你可以使用break聲明。