java - 陷入无限循环来计算尝试次数,建议吗?

标签 java for-loop

所以我正在制作一个简单的猜谜游戏,它创建一个 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/

相关文章:

javascript - For 循环在 D3.js 中不起作用

java - 如何在不退出应用程序的情况下根据 JPanel 上的事件关闭特定的 JFrame?

javax/servlet/jsp/tagext/TagLibraryValidator - 运行 Web 项目

java - 如何成功获取外部IP

C语言: Write a program that would take 30 integers and prints the largest number and the smallest number

c++ - 我应该通过迭代器还是通过访问运算符来迭代 vector ?

java - Android Google Maps API v2 中的用户位置标记

java - 如何在 bukkit 中存储变量的变量?

python - 如何在 Python for 循环中使用多个变量?

python - if block 中不支持的操作数类型 TypeError