Java中使用函数创建一个简单的猜数字游戏
发布时间:2023-06-30 22:29:11
下面是使用函数创建一个简单的猜数字游戏的Java代码。
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到猜数字游戏!");
int maxNumber = 100;
playGame(maxNumber);
System.out.println("再玩一次?(y/n)");
String playAgain = scanner.nextLine();
if(playAgain.equalsIgnoreCase("y")){
playGame(maxNumber);
}
System.out.println("游戏结束。");
scanner.close();
}
private static void playGame(int maxNumber){
Random random = new Random();
int targetNumber = random.nextInt(maxNumber) + 1;
Scanner scanner = new Scanner(System.in);
int guess;
int attempts = 0;
boolean isCorrect = false;
while (!isCorrect){
System.out.print("请猜一个 1 到 " + maxNumber + " 之间的数字:");
guess = scanner.nextInt();
attempts++;
if(guess < targetNumber){
System.out.println("你猜的数字太小了,请再试一次。");
}else if(guess > targetNumber){
System.out.println("你猜的数字太大了,请再试一次。");
}else{
System.out.println("恭喜你,猜对了!");
System.out.println("你总共猜了 " + attempts + " 次。");
isCorrect = true;
}
}
}
}
在这个简单的猜数字游戏中,程序会通过Random类生成一个位于1到maxNumber之间的随机数作为目标数。玩家可以通过输入自己的猜测来猜出这个数。
游戏的流程如下:
1. 程序首先会打印出欢迎消息,并设置maxNumber为100(你可以根据需要修改这个值)。
2. 然后调用playGame函数来开始一个新游戏。
3. 在playGame函数中,程序首先使用Random类生成一个1到maxNumber之间的随机数作为目标数。
4. 然后使用Scanner类获取玩家的猜测,判断猜测与目标数的大小关系,并通过打印出不同的提示信息告诉玩家。
5. 如果玩家猜对了,程序会打印出恭喜消息并告诉玩家猜了多少次。
6. 如果玩家猜错了,程序会继续循环直到玩家猜对为止。
7. 当游戏结束时,程序会询问玩家是否再玩一次。如果玩家输入"y",程序会再次调用playGame函数。
8. 游戏结束后,程序会打印出游戏结束的消息并关闭Scanner。
你可以根据自己的需要对代码进行修改和扩展,例如添加一些游戏难度级别、记录玩家的 成绩等。
