我目前正在用Java制作高低猜猜游戏。我相信我有两个问题阻碍了游戏的正常运行。

首先,我在playGame方法中有一个while语句,它不会像现在这样改变,而且我很难理解如果做出正确的猜测,如何使它改变。据我了解,我无法更改boolean bool = true的值;从GiveResponse方法开始,是否必须从同一方法playGame完成?是否有比使用while语句更好的方法呢?

其次,当做出正确的猜测并且playGame方法将参数guessCount的值返回给main方法时,应该将其打印出来。我对这款游戏的说明说,返还后应该用main方法打印出来。

import java.io.Reader;
import java.util.Scanner;
public class HiLo2 {
 public static void main(String[] args) {

  System.out.println("Decide a level of difficulty\r"
    + "1. 1-10 \r"
    + "2. 1-100 \r"
    + "3. 1-1000");

  Scanner reader = new Scanner(System.in);
  int n = reader.nextInt();

   if (n==1) {
             playGame(10);
   }
         else if (n==2) {
             playGame(100);
         }
         else if (n==3) {
          playGame(1000);
         }
         else {
          System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
         }
  }

 public static int playGame(int maxNumber) {
  int answer = (int)(Math.random() * maxNumber) +1;
  int guessCount = 0;
  boolean bool = true;
  Scanner reader = new Scanner(System.in);
  System.out.println("Guess a number between 1 and " + maxNumber);

  while (bool) {
  int guess = reader.nextInt();
  guessCount = guessCount + 1;
  giveResponse(answer, guess);
  }

  return guessCount;
 }

 public static void giveResponse(int answer, int guess) {
  if (guess == answer) {
   System.out.println("Your guess is correct!\r");
  }
  else if (guess > answer) {
   System.out.println("Your guess is too high, guess again:\r");
  }
  else if (guess < answer) {
   System.out.println("Your guess is too low, guess again:\r");
  }
 }
}


我希望问题清楚明确。任何朝着正确方向的指针都值得赞赏。

最佳答案

您可以让GiveResponse方法返回一个布尔值

static boolean giveResponse(...)


并将return false;放在if (guess == answer){例中,并将return true放在方法末尾。代替使用giveResponse作为void方法,而使用bool = giveResponse(answer,guess)

对于第二个问题,在if语句之前的main方法中添加一个int numberOfGuesses,并使用numberOfGuesses = playGame(...)调用playGame,然后调用System.out.println(“您猜到了” + numberOfGuesses +“次。 );在if语句之后。

07-26 09:30