用Java写一个猜数游戏代码
时间: 2023-05-23 13:02:22 浏览: 103
好的,以下是用 Java 写一个猜数游戏的代码:
import java.util.Scanner;
import java.util.Random;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int secretNumber = rand.nextInt(101);
int numAttempts = 0;
int guess = -1;
System.out.println("猜数游戏!我生成了一个 0-100 之间的数字,请猜猜是多少?");
while(guess != secretNumber) {
System.out.print("你猜的数字是:");
guess = input.nextInt();
numAttempts++;
if(guess < secretNumber) {
System.out.println("太小了,再试试!");
} else if(guess > secretNumber) {
System.out.println("太大了,再试试!");
} else {
System.out.println("恭喜你,猜对了!");
System.out.println("你总共猜了 " + numAttempts + " 次。");
}
}
}
}
希望这个代码对你有帮助!
阅读全文