java输入数字猜测
时间: 2024-09-21 21:05:54 浏览: 39
java实现数字炸弹
在Java中,你可以通过控制台输入让用户猜数字,通常用于练习基本的用户交互。下面是一个简单的示例,目标数字隐藏起来,用户输入他们的猜测,然后程序判断并给出提示:
```java
import java.util.Scanner;
public class GuessNumberGame {
private int secretNumber;
private int attempts;
public GuessNumberGame(int secret) {
this.secretNumber = secret;
this.attempts = 0;
}
public void startGame() {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到猜数字游戏,我在心里想了一个1到100之间的数。");
while (true) {
System.out.print("请输入你的猜测:");
int guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("太小了,再试一次!");
} else if (guess > secretNumber) {
System.out.println("太大了,再试试!");
} else {
System.out.printf("恭喜你,猜对了!尝试次数:%d\n", attempts);
break;
}
}
scanner.close();
}
public static void main(String[] args) {
GuessNumberGame game = new GuessNumberGame(50);
game.startGame();
}
}
阅读全文