value不是从另一个类返回的

时间:2017-12-05 06:31:54

标签: java debugging

您好我正在制作一个玩家遇到机器人的游戏,机器人要求它猜测1-10之间的数字。玩家有三次尝试或者他们死了。我已经编写了所有代码并且猜测工作正常,但无论何时播放正确,他仍然会死。我添加了几个print语句来查看我的代码返回的值,它似乎返回了错误的值。有人可以帮我吗?感谢。

从这门课开始

if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
 System.out.print("IT'S GAME OVER MAN!\n");
    System.exit(0);
}
else {
  System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
      int answer = 0;
      john[choice].toPass(answer);
      if (answer== 1) {
         System.out.println(answer);
          map[x][y].removeJohnPlayer();
         }
      else { System.out.println(answer);
        System.out.print("IT'S GAME OVER MAN!\n");
  System.exit(0);
  }

到这个班级

public int toPass(int right){


    int hiddenNum = numram.nextInt(MAX_NUMBER);

    Scanner input = new Scanner(System.in);

    int numOfGuesses = 0;
    int a = right;

    do {
        System.out.println("Enter a number by guessing: ");

        int guessedNum = input.nextInt();
        numOfGuesses++; 

        if (guessedNum == hiddenNum) {
            System.out.println("Darn! Your number is matched. You may live.");
            System.out.println("You have made " + numOfGuesses + " attempts to find the number!");

            a = 1;
             break;

        } else if (guessedNum < hiddenNum) {
            System.out.println("Try a bigger number");


        } else if (guessedNum > hiddenNum) {
            System.out.println("Try a smaller number");

        }    

}   while (numOfGuesses < 3);
System.out.println(a);
return a;

}

1 个答案:

答案 0 :(得分:1)

下面

john[choice].toPass(answer);

您忽略了toPass方法返回的值。

将其更改为:

answer = john[choice].toPass(answer);
顺便说一下,没有理由将参数传递给你的toPass方法,因为它没有使用它,也无法改变它(因为Java是一种值传递语言)。返回值就足够了。

即。将您的方法更改为public int toPass()

您应该进行的另一项更改是将返回类型更改为boolean。返回truefalse比返回10更具可读性。