下面是一个简单的Java沙盒游戏,您可以将其复制到您的Java IDE中并进行修改和扩展。
1.创建一个Java类,命名为“GuessingGame”,在其中添加以下代码:
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
int secretNumber = (int) (Math.random() * 100) + 1;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Welcome to the guessing game!");
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.println("Can you guess what it is?");
do {
System.out.print("Enter your guess: ");
guess = input.nextInt();
tries++;
if (guess < secretNumber) {
System.out.println("Too low! Try again.");
} else if (guess > secretNumber) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations, you guessed the number in " + tries + " tries!");
}
} while (guess != secretNumber);
input.close();
}
}
运行代码,您将看到以下输出:
Welcome to the guessing game!
I'm thinking of a number between 1 and 100.
Can you guess what it is?
Enter your guess:
3.输入您猜测的数字并按回车键。如果您猜测的数字低于或高于秘密数字,程序将提示您尝试再猜一次。如果您猜测的数字与秘密数字相同,程序将祝贺您并告诉您您猜测的次数。
这就是一个简单的Java小游戏的代码,希望您喜欢!
--------by ChatGPT