在数字猜谜游戏中用FOR循环实现/替换WHILE循环

时间:2019-04-12 13:27:08

标签: java

因此对于我的Java编程类,评估之一是以下(一个经典的数字猜测游戏):

  

编写一个程序,使用该程序玩Hi­Lo猜谜游戏   数字。该程序应选择11(含)和88(不含)之间的随机数,然后   反复提示用户猜测数字。每次猜测时,向用户报告他或她是   正确或猜测是高还是低。继续接受猜测,直到用户正确猜测为止或   选择退出。使用前哨值来确定用户是否要退出。数数   当用户正确猜测时猜测并报告该值。在每局游戏结束时(退出或   正确的猜测),提示确定用户是否要再次玩。继续玩游戏   直到用户选择停止。您需要至少正确使用while循环和for循环。

到目前为止,使用WHILE和IF函数,游戏可以正常运行。但是,为了在我的解决方案上获得满分,它要求我至少使用一个FOR循环,但是我很难做到这一点。

import java.util.*;
public class Guessing {
    public static void main (String[] args)
 {
 //Setting up the variables
 final int MAX = 88;
 final int MIN = 11;
 int answer, guess = 1;
 String another="Y";

 //Intializing scanner and random
 Scanner scan = new Scanner (System.in);
 Random generator = new Random();
 //play again loop
 while (another.equalsIgnoreCase("Y"))
 {
    //Generate a random number between 11 and 88
    answer = generator.nextInt(MAX-MIN)+11;

    System.out.print ("Guess the number I picked between "+MIN+" and "
               + MAX + "!\n");

    while(guess!=answer)
    {
       System.out.println("Enter your guess: ");
       guess = scan.nextInt();
       System.out.println(answer);

       if (guess<answer && guess != 0)
           System.out.println("Your guess was too low! (0 to exit) ");
       else if (guess>answer)
           System.out.println("Your guess was too high!(0 to exit) "); 
       else if (guess==0){
           System.out.println("You excited the current round.");
           break;}
       else{ 
           System.out.println("Your guess was correct!");
           break;}
       }
    }
    //Asking player to play another game
    System.out.println("Do you want to play another game?(Y|N)");
    another = scan.next();
    if (another.equalsIgnoreCase("N"))
        System.out.println("Goodbye, thank you for playing");
 }
}
}

到目前为止,该程序可以运行。它正确地给出了较高/较低的建议,当输入0作为猜测时,当前回合将停止,您可以使用Y / N开始另一回合。但是我正在努力用FOR循环替换功能/循环之一。

2 个答案:

答案 0 :(得分:0)

您可以用for循环代替中央while循环,也可以用来计算迭代次数

for(int i=0;;i++)
{
   System.out.println("Enter your guess: ");
   guess = scan.nextInt();
   System.out.println(answer);

   if (guess<answer && guess != 0)
       System.out.println("Your guess was too low! (0 to exit) ");
   else if (guess>answer)
       System.out.println("Your guess was too high!(0 to exit) "); 
   else if (guess==0){
       System.out.println("You excited the current round.");
       break;}
   else{ 
       System.out.println("Your guess was correct!\n");
       System.out.println("It took "+i+" guesses to get the answer");
       break;}
   }
}

此for循环是一个无限循环,因为它没有第二个参数。但是,由于最后的else中断,给出正确答案后,您的程序将退出for循环。

答案 1 :(得分:0)

随着猜测次数的增加,人们可以在其上使用for循环。 通常,人们会写for (int i = 0; i < n; ++i) {,但在这里我们想知道for循环之后的循环计数器,必须在之前声明它:

int numberOfGuesses = 0;
for (; guess != 0 && guess != answer; numberOfGuesses++) {
}
... numberOfGuesses

除了找到答案或退出外,没有其他上限。

for (PARTA; PARTB; PARTC)中的所有三个部分都是可选的。