我做了一个简单的猜测游戏,但我不知道怎么问玩家是否想再次玩游戏。每次游戏结束我都要再次运行游戏所以我想要添加此功能。我查看了其他一些帖子,但他们没有帮助。这是代码:
import java.util.*;
public class guessNumber{
private static Scanner userInput = new Scanner(System.in);
public guessNumber(){
System.out.println("~~~Guess Game~~~");
}
public void guessGame(){
System.out.println("Enter the maximum number:");
int maxNum = userInput.nextInt();
System.out.println("Guess a number between 0 and " + maxNum + ":");
int randomNumber = (int) (Math.random() * maxNum);
boolean gameOn = true;
int numberOfTries = 0;
while(gameOn){
boolean printOthers = true;
numberOfTries++;
int number = userInput.nextInt();
if(number > maxNum){
System.out.println("Please enter a number between 0 and " + maxNum + ".");
printOthers = false;
}
if(printOthers){
if(number == randomNumber){
System.out.println("=================================");
System.out.println("You guessed the right number xD.");
System.out.println("Your tried " + numberOfTries + " times.");
System.out.println("=================================");
}else if(number > randomNumber){
System.out.println("Try a lower number");
}else if(number < randomNumber){
System.out.println("Try a higher number");
}
else{
System.out.println("Please enter a number between 0 and " + maxNum + ".");
}
}
}
}
public static void main(String[] args){
guessNumber guess = new guessNumber();
guess.guessGame();
}
}
答案 0 :(得分:1)
在你的主要使用while循环。在循环中首先调用你的guessGame()然后,类似于你要求输入一个数字,你问他们是否想要再次玩(Y / N?),如果他们说不,你就打破了循环,否则你继续...
答案 1 :(得分:1)
使用while循环在main方法中添加调用方法
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
do{
//call your game
System.out.println("Do you want to play again. Press y");
}
while(scanner.next().equals("y"));