java猜数字代码实现
时间: 2023-11-20 07:51:26 浏览: 83
好的,以下是一个简单的 Java 猜数字游戏的代码实现:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1;
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (numberOfTries < 10) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
System.out.println("Congratulations! You guessed the number in " + numberOfTries + " tries!");
win = true;
break;
} else if (guess < numberToGuess) {
System.out.println("The number is higher than " + guess + ". Try again.");
} else {
System.out.println("The number is lower than " + guess + ". Try again.");
}
}
if (!win) {
System.out.println("Sorry, you ran out of tries. The number was " + numberToGuess + ".");
}
}
}
```
这个程序会随机生成一个 1 到 100 的整数,然后让用户在 10 次机会内猜出这个数字。如果用户猜对了,程序会输出猜对的次数并结束游戏;如果用户用完了所有机会还没有猜对,程序会输出正确答案并结束游戏。
阅读全文