/你好,我正在嘗試學習如何在java中使用「break」commend以及用「y或n」選項繼續循環。我正在寫這個遊戲猜數字,我在選擇「y」時遇到了一些麻煩。我會試着解釋一下,編寫一個猜數字的遊戲很容易,所以我開始添加一些條件,如可能性和再次玩或不玩,後來我認爲如果增加退出任何可能性會更有趣玩家希望的時間,但這不能正常工作。請幫助,這就是我的代碼關於猜測的非常簡單的遊戲
package guessinggame;
import java.util.Random;
import java.util.Scanner;
/**
*
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(" Welcome ");
Random rand = new Random();
Scanner input = new Scanner(System.in);
boolean play_again = true;
while (play_again)
{
int number_guess = rand.nextInt(100)+1;
int number_of_tries = 0;
int guess;
String another = "y";
boolean win = false;
while (win == false)
{
System.out.println(" Try too guess a number between 1 and 100 ");
guess = input.nextInt();
number_of_tries++;
if (guess == number_guess)
{
win = true;
}
else if (guess < number_guess)
{
System.out.println(" Guess is too low " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
else if (guess > number_guess)
{
System.out.println(" Guess is too high " + "\n Guess another number to continue or n to quit ");
if (input.hasNext("n"))
{
play_again = false;
break;
}
}
}
System.out.println(" You Win!!! ");
System.out.println(" The number was " + number_guess);
System.out.println(" It took you " + number_of_tries + " tries " +
"\nWould you like to play again? (y/n): ");
if (another.equalsIgnoreCase("y") == true)
play_again = true;
else
{
play_again = false;
}
}
}
}
不是真的關係到你的問題,但你應該看看[Java命名約定(http://www.oracle.com/technetwork/java/codeconventions-135099.html#367) – redFIVE
如果我看到它,你的代碼打印「你贏了」,當你中止循環。使用'return'而不是break來立即退出。 – PMF
考慮粘貼代碼片段而不是整個班級。在問這裏之前,最好自己縮小問題的範圍;這樣你就會知道哪幾行代碼是罪魁禍首。 –