以下代碼,我需要通過鍵入單詞「quit」來停止代碼,但不使用「break」或「system.exit」語句。任何人都可以幫助我?我認爲布爾可以解決這個問題,但我不知道如何使用它。 我把quit語句放在循環的前兩行, ,但我不知道它是否屬於那裏。即時消息在我的學習階段,所以不要太嚴格:))Java遊戲。需要停止代碼而不使用break語句或system.exit
import java.util.*;
public class Game {
public static void main (String[]args){
Game guessing = new Game();
guessing.start();
}
public void start() {
System.out.println("Welcome to guessing game!");
System.out.println("Please enter the number between 1 and 1000");
Scanner input = new Scanner(System.in);
String playerName;
String currentGuess;
String quit = "quit";
boolean playGame = true;
int tries = 0; //number of times player guessed
int guess = 0; //number that player inputs
long startTime = System.currentTimeMillis(); //start timer after first guess
int randomNumber = (int) (Math.random() * 999 + 1); // generating random number
System.out.println(randomNumber); // to be deleted after game is finished
currentGuess = input.nextLine();
do{
if (currentGuess.equalsIgnoreCase(quit)) {
System.out.println("Thanx for playing");}
if (currentGuess.matches("[0-9]+")) {
int PlayerGuessInt = Integer.parseInt(currentGuess);
}
else {
System.out.println("You have netered non-numeric value,please try again");
currentGuess = input.nextLine();
continue;
}
guess = Integer.parseInt(currentGuess);
if(guess<1 || guess>1000){
System.out.println("The number is out of range! Please try again");
currentGuess = input.nextLine();
continue;
}
if (guess>randomNumber){
System.out.println("Oops,too high!");
currentGuess = input.nextLine();
tries++;
}
else if (guess<randomNumber){
System.out.println("Sorry, to low!");
currentGuess = input.nextLine();
tries++;
}
}
while (guess!=randomNumber);
if (guess==randomNumber){
tries++;
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Well done! You won the game in " + tries + " guesses " + "and " + gameTime/1000 + " seconds!");
System.out.println("Please enter your name: ");
playerName = input.nextLine();
}
}
}
你的意思是'return;'? –
因爲在這段時間內沒有'break'語句,所以'while'後面的'if'不需要'if'。它永遠是'真實的'。 – techfoobar
設置循環條件的布爾部分,並在循環停止時將其設置爲false。 –