【问题标题】:Guess 7 times loop (Basic Java)猜 7 次循环(Java 基础)
【发布时间】:2020-02-07 10:22:54
【问题描述】:

我正在研究 1-100 的猜数,如果猜错了 7 次就会输掉比赛,除非你猜对了数字。我尝试使用 while 循环添加 if 语句 if (guess1 <8) break; 应该停止或中断我使用的正在运行的程序是 Unix Terminal。

import java.util.Random;
import java.util.Scanner;

public class Games {
   public static void main(String[] args){

      Scanner input = new Scanner(System.in);

      Random rand = new Random();
      int tries;
      int correctNum = rand.nextInt(100);
      int count = 7;

      //int guess1 = input.nextInt();
      while(true){

         System.out.println("Pick a number between 1-100");
         int guess1 = input.nextInt();

         if(guess1 < correctNum){
            System.out.println("Too low!");
         } else if(guess1 > correctNum){
            System.out.println("Too high!");
         } else if(guess1 == correctNum){
            System.out.println("Correct!");
         } else{
            System.out.println("hmm, try again");
         }

         if (guess1<8) break;
      }
   }
}

【问题讨论】:

  • 其实,guess1 是用户输入的 Input,要循环检查的变量是 count。您应该从 1 而不是 7 开始计数,并在每次迭代时递增它。您也可以在while(count &lt; 8){ 中设置您的条件,而不是 `if (guess1
  • Games.java:15: error: cannot find symbol while(guess1 &lt; 8){ ^ symbol: variable guess1 location: class Games 1 error
  • guess1 是用户输入的输入。创建另一个变量来跟踪attempts 您也可以在此处使用do while。它执行代码,然后检查条件。 while 检查条件然后执行代码。

标签: java loops while-loop


【解决方案1】:

while(true) 改为for循环,只迭代7次。

for (int i = 0; i < 7; ++i) {

    //Remove the if (guess1<8) break;
}

【讨论】:

    【解决方案2】:

    您的休息条件不正确。要跟踪循环运行了多少次,您可能需要初始化 tries 并在循环中将其加一。还要将if (guess1&lt;8) break;更改为if (tries &gt; count) break;,以确保循环不会运行超过count (7) 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多