所以我正在制作一个简单的猜谜游戏,它创建一个 1 到 100 之间的随机数,用户必须以尽可能少的尝试来解决它。我遇到的问题是我的 for 循环不断循环以计算用户已完成的尝试次数。
import java.util.Scanner;
import java.util.Random;
class prog{
public static void main(String[] args){
Random rand = new Random();
int randNum = rand.nextInt(100) + 1;
System.out.println("I am thinking of a number from 1 to 100 ... guess what it is ?");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
for (int tries = 0; i>=0; tries++){
if (i<randNum){
System.out.println("Higher!");
}
else if (i == randNum){
System.out.println("You got it! Congrats! It took you " + tries + " tries!");
}
else if (i>randNum){
System.out.println("Lower!");
}
}
}
}
最佳答案
只要 i
大于或等于零,您就会循环,它总是如此,因为您不会将 i
从零更改。您需要输入上限,或者在循环内进行一些检查,然后打破
跳出循环。
关于java - 陷入无限循环来计算尝试次数,建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21196041/