坚持无限循环来计算尝试,建议?

时间:2014-01-17 21:17:31

标签: 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!");
   }
  }
 }
}

2 个答案:

答案 0 :(得分:1)

只要i大于或等于零,就会循环,这将永远是,因为您不会将i从零更改。你需要设置一个上限,或者在你break循环的循环中进行一些检查。

答案 1 :(得分:0)

您只需添加数字尝试...所以i永远不会少于0.事实上,您永远不会重新分配i。试试这个,

else if (i == randNum){
  System.out.println("You got it! Congrats! It took you " + tries +  " tries!");
  break;
} else if (i>randNum){
  System.out.println("Lower!");
}
i = sc.nextInt(); // <-- at the bottom of your for loop.