简体   繁体   English

Println打印多次,而不是每次循环都增加

[英]Println printing multiple times instead of increasing for each loop

I'm trying to make this code print out the number of games played ( gameNum ). 我正在尝试使此代码打印出玩过的游戏数量( gameNum )。 Instead, it always sets gameNum to 2 , and prints out the last println the number of times that the game was played. 而是始终将gameNum设置为2 ,并打印出最后一次println玩游戏的次数。 I feel like I made a dumb mistake here, but I am having trouble finding it. 我觉得我在这里犯了一个愚蠢的错误,但是我很难找到它。 Could you please give me a hint instead of the answer? 您能给我一个提示而不是答案吗? I'd like to figure this out on my own. 我想自己解决这个问题。 If not, then feel free to go ahead and write the answer. 如果没有,请随时写答案。

Thanks! 谢谢!

import java.util.*;

public class Testing_gameNum {
    public static final int amt = 1;
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        guessCounter(console);
    }

    public static int game(Scanner console) {
        Random rand = new Random();
        int guess = 0;
        int guessNum = 0;
        System.out.printf("I'm thinking of a number...", amt);
        System.out.println();
        int num = 1;

        do {
            System.out.println("Your guess? ");
            guess = console.nextInt();
            guessNum += guessNum;
        } while (guess != num);

        return guessNum;
    }

    public static void guessCounter(Scanner console) {
        int gameNum = 1;
        int guessNum = game(console);
        if (guessNum == 1){
            System.out.printf("You won in %d guesses!", guessNum);
            System.out.println();
        }
        gameNum = gameNum + 1;
        System.out.println("Do you want to play again?");
        String play = console.next();
        if (play.equals("y")) {
            guessCounter(console);
        }
        System.out.println("Number of games: " + gameNum);
    }
}
  • Check for every place gameNum is used. 检查每个使用gameNum地方。 I found it ie in the method guessCounter(Scanner console) - and only there. 我在方法guessCounter(Scanner console)找到了它,并且仅在那里。
  • So every time you call this method, the value of gameNum is initialized to 1. After the game is won, you increment it by 1 and later on print it, hence the 2 in the output. 因此,每次调用此方法时, gameNum的值gameNum初始化为1。赢得游戏后,将其递增1,然后在打印时递增,因此输出为2。
  • Move int gameNum = 1; Move int gameNum = 1; out of the method guessCounter(Scanner console) . 超出方法guessCounter(Scanner console) This should help. 这应该有所帮助。

Aside of this please review also the code block 除此之外,还请查看代码块

if (play.equals("y")) {
  guessCounter(console);
}

Imagine a player goes on and on, always selecting "y". 想象一个玩家不断前进,总是选择“ y”。 With every game round, you create another level of recursion. 在每一轮游戏中,您都会创建另一个递归级别。 This "do you want to play again" could be implemented by a do-while loop, this will avoid the recursion. 可以通过do-while循环实现此“您想再次播放”吗,这将避免递归。

Try something like this: 尝试这样的事情:

public class Testing_gameNum
{
   public static final int amt = 1;
   public static void main(String[] args)
   {
      Scanner console = new Scanner(System.in);
      guessCounter(console);
   }

   public static int game(Scanner console)
   {
      Random rand = new Random();
      int guess = 0;
      int guessNum = 0;
      System.out.printf("I'm thinking of a number...", amt);
      System.out.println();
      int num = 1;
      do
      {
         System.out.println("Your guess? ");
         guess = console.nextInt();
         guessNum += amt;
      }
      while (guess != num);
      return guessNum;
   }
   public static void guessCounter(Scanner console)
   {
      int gameNum = 1;
      do
      {
         int guessNum = game(console);
         if (guessNum == 1)
         {
            System.out.printf("You won in %d guesses!", guessNum);
            System.out.println();
         }
         gameNum = gameNum + 1;
         System.out.println("Do you want to play again?");
         String play = console.next();
      }
      while (play.equals("y"))
      System.out.println("Number of games: " + gameNum);
   }
}

You've defined guessCounter to be a recursive method, but that's probably not what you want for several reasons. 您已经将guessCounter定义为递归方法,但是由于多种原因,这可能不是您想要的。 First, each time you call guessCounter , you're creating a new gameNum and setting it to 1 . 首先,每次调用guessCounter ,都要创建一个新的gameNum并将其设置为1 You play the game and increment it to 2 , but then recurse and never touch that variable again, which is the cause of your bug. 您在玩游戏并将其增加到2 ,但是然后递归并且再也不要触摸该变量,这就是导致您的错误的原因。 Additionally, (although this is unlikely to happen in usual play), you could overflow your stack if you play the game enough times. 此外,(尽管这不太可能在常规游戏中发生),但如果您玩游戏足够多的时间,则可能会使堆栈溢出。 Each time you play the game, the computer needs to remember the point in code that it needs to return to when it completes that call of guessCounter . 每次玩游戏时,计算机都必须记住完成对guessCounter调用时需要返回的代码点。 Eventually you will run out of memory to store those pointers. 最终,您将用光内存来存储那些指针。 Recursion is good for certain problems, but it's better to use loops most of the time. 递归对于某些问题很有用,但是大多数时候最好使用循环。

How about using a loop rather than recursion. 如何使用循环而不是递归。

I solved my question! 我解决了我的问题! Here's the code (explanation below): 这是代码(下面的解释):

public class Testing_gameNum {
    public static final int amt = 1;
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        guessCounter(console);
    }

    public static int game(Scanner console) {
        Random rand = new Random();
        int guess = 0;
        int guessNum = 0;
        System.out.printf("I'm thinking of a number...", amt);
        System.out.println();
        int num = 1;

        do {
            System.out.println("Your guess? ");
            guess = console.nextInt();
            guessNum ++;
        } while (guess != num);

        return guessNum;
    }

    public static void guessCounter(Scanner console) {
        int gameNum = 0;
        String play = "y";
            do {
                int guessNum = game(console);
                gameNum += 1;
                if (guessNum == 1) {
                    System.out.printf("You won in %d guesses!", guessNum);
                    System.out.println();
                }
                System.out.println("Do you want to play again?");
                play = console.next();
            } while (play.equals("y"));
        System.out.println("Number of games: " + gameNum);
    }
}

MY PROBLEMS: gameNum was resetting each time I called guessCounter . 我遇到的问题: gameNum每次被我称为复位guessCounter I needed a do/while loop; 我需要一个do/while循环; that way, I could initialize gameNum inside the method, and then loop only the section of the method that needed to be repeated. 这样,我可以在方法内部初始化gameNum ,然后仅循环需要重复的方法部分。 The repetitive println was linked with that same issue: it was reprinted each time I called guessCounter , as opposed to just the part of the code I wanted repeated. 重复的println与相同的问题有关:每次我调用guessCounter ,它都会被重新打印,而不仅仅是我想要重复的部分代码。

Thanks for your help, everyone! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM