java for循环猜数字
时间: 2023-11-04 17:00:44 浏览: 105
Java中的for循环可以用于实现猜数字小游戏。在这个游戏中,可以使用一个for死循环让用户一直猜数字,直到猜对为止。以下是一个实现猜数字小游戏的示例代码:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
System.out.println("猜数字小游戏(范围0-20)");
Random random = new Random();
int targetNumber = random.nextInt(20);
for (;;) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入您猜的数字:");
int guessNumber = scanner.nextInt();
if (guessNumber < targetNumber) {
System.out.println("您猜小了。");
} else if (guessNumber > targetNumber) {
System.out.println("您猜大了。");
} else {
System.out.println("恭喜您!您猜对了!");
break;
}
}
}
}
```
这段代码中,我们使用了一个无限循环`for(;;)`,并在循环体中让用户输入猜测的数字。根据用户输入的数字与目标数字的大小关系,输出相应的提示信息。当用户猜对数字时,跳出循环并输出恭喜信息。通过这样的方式,用户可以一直猜测直到猜对为止。
阅读全文
相关推荐















