【发布时间】:2016-02-08 22:22:54
【问题描述】:
我遇到的问题是是/否语句,如果我输入“否”,它将继续退出程序。 请如果有人可以给我提示问题在哪里?
导入 java.util.Random; 导入 java.util.Scanner;
公开课 NumberGame { 私有静态最终 int DO_NOT_PLAY_AGAIN = 0;
private final Scanner mScanner;
private final Random mRandom;
private String mUserName;
private int mCorrectAnswer;
private int mPlayAgainInput;
private String mAnswer;
public NumberGame() {
mScanner = new Scanner(System.in);
mRandom = new Random();
}
public void run() {
displayWelcomeMessage();
getUserName();
greetUser();
getAnswer();
do {
intNumberGuessGame();
} while (mPlayAgainInput != DO_NOT_PLAY_AGAIN);
sayGoodbye();
}
private void getAnswer(){
System.out.println("Would you lioke to play a game enter yes to play or no to exit a game");
mAnswer = mScanner.nextLine();
if (mAnswer.equals("no"))
System.out.println("Maybe next time");
sayGoodbye();
}
private void displayWelcomeMessage() {
System.out.println("Welcome to the game!");
System.out.println("To play this game you have to"
+ " guess a number and enter upon prompt or you can"
+ " enter 0 to quit the game.");
}
private void getUserName() {
System.out.println("Enter your user name: ");
mUserName = mScanner.nextLine();
}
private void greetUser() {
System.out.println("Let's play a game, " + mUserName + ".");
}
private void sayGoodbye() {
System.out.println("Thanks for playing, " + mUserName + "!");
}
private void intNumberGuessGame() {
// Get a random number between 1 - 100
Random generator = new Random();
mCorrectAnswer = mRandom.nextInt(100) + 1;
int theirGuess = 0;
int howManyTries = 0;
while (theirGuess != mCorrectAnswer) {
System.out.println("Guess my number: ");
theirGuess = mScanner.nextInt();
mCorrectAnswer = mRandom.nextInt(101) + 1;
howManyTries++;
System.out.println("Correct answer = " + mCorrectAnswer);
if (theirGuess == mCorrectAnswer) {
System.out.println("You guessed it! It only took you "
+ howManyTries + " tries to get it right!");
promptToPlayAgain();
// They won the game, exit current loop
break;
} else if (theirGuess > mCorrectAnswer) {
System.out.println("Your answer is too high.");
} else if (theirGuess < mCorrectAnswer) {
System.out.println("Your answer is too low.");
}
}
}
private void promptToPlayAgain() {
System.out.println("Do you want to play again? (0 to quit): ");
mPlayAgainInput = mScanner.nextInt();
}
}
public class MainApp {
public static void main(String[] args) {
new NumberGame().run();
}
}
【问题讨论】:
-
你的哨兵是零,基于
mPlayAgainInput = mScanner.nextInt();。你为什么假设如果它扫描为“否”就会退出游戏? -
这是我有问题的部分,private void getAnswer(){ System.out.println("你想玩游戏输入是玩还是不退出游戏"); mAnswer = mScanner.nextLine(); if (mAnswer.equals("no")) System.out.println("也许下次");说再见(); }
标签: java