【问题标题】:Calling local variables in other static methods?在其他静态方法中调用局部变量?
【发布时间】:2014-10-28 23:49:55
【问题描述】:

我应该编写一个程序,在用户给定的约束之间选择一个随机数,并要求用户输入关于这个数字是什么的猜测。该程序向用户反馈该数字是高于还是低于用户的猜测。记录猜测次数、游戏次数、所有游戏中使用的总猜测次数以及一场游戏中使用的最低猜测次数。

这些结果被打印出来。负责运行游戏的函数 (playGame()) 和负责打印这些结果的函数 (getGameResults()) 必须在两个单独的方法中。

我的问题是,我不确定如何将在 playGame() 方法的整个过程中修改的局部变量获取到 getGameResults() 方法。

getGameResults() 打算在另一个方法 continuePlayTest() 中调用,该方法测试用户的输入以确定他们是否希望继续玩游戏,所以我认为调用 getGameResults() 不会起作用,否则此测试也将不起作用。除非我在 playGame() 中调用 continuePlayTest(),但 continuePlayTest() 在其代码中调用 playGame(),这样会使事情复杂化。

我们只能使用我们学到的概念。我们不能在前面使用任何概念。 到目前为止,我们已经学习了如何使用静态方法、for 循环、while 循环、if/else 语句和变量。全局变量的风格不好,所以不能使用。

代码:

public class Guess {
public static int MAXIMUM = 100;

public static void main(String[] args) {
    boolean whileTest = false;
    gameIntroduction();
    Scanner console = new Scanner(System.in);
    playGame(console);
}

// Prints the instructions for the game.
public static void gameIntroduction() {
    System.out.println("This process allows you to play a guessing game.");
    System.out.println("I will think of a number between 1 and");
    System.out.println(MAXIMUM + " and will allow you to guess until");
    System.out.println("you get it. For each guess, I will tell you");
    System.out.println("whether the right answer is higher or lower");
    System.out.println("than your guess.");
    System.out.println();       
}

//Takes the user's input and compares it to a randomly selected number. 
public static void playGame(Scanner console) {
    int guesses = 0;
    boolean playTest = false;
    boolean gameTest = false;
    int lastGameGuesses = guesses;
    int numberGuess = 0;
    int totalGuesses = 0;
    int bestGame = 0;
    int games = 0;
    guesses = 0;
    games++;
    System.out.println("I'm thinking of  a number between 1 and " + MAXIMUM + "...");
    Random number = new Random();
    int randomNumber = number.nextInt(MAXIMUM) + 1;
    while (!(gameTest)){
        System.out.print("Your guess? ");
        numberGuess = console.nextInt();
        guesses++;
        if (randomNumber < numberGuess){
            System.out.println("It's lower.");
        } else if (randomNumber > numberGuess){
                System.out.println("It's higher.");
            } else {
        gameTest = true;
        }
        bestGame = guesses;
        if (guesses < lastGameGuesses) {
            bestGame = guesses;
        }
    }
    System.out.println("You got it right in " + guesses + " guesses");
    totalGuesses += guesses;
    continueTest(playTest, console, games, totalGuesses, guesses, bestGame);
}


public static void continueTest(boolean test, Scanner console, int games, int totalGuesses, int guesses, int bestGame) {
    while (!(test)){
        System.out.print("Do you want to play again? ");
        String inputTest = (console.next()).toUpperCase();
        if (inputTest.contains("Y")){
            playGame(console);
        } else if (inputTest.contains("N")){
            test = true;
            }
        }
    getGameResults(games, totalGuesses, guesses, bestGame);
    }       

// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
    System.out.println("Overall results:");
    System.out.println("\ttotal games   = " + games);
    System.out.println("\ttotal guesses = " + totalGuesses);
    System.out.println("\tguesses/games = " + ((double)Math.round(guesses/games) * 100)/100);
    System.out.println("\tbest game     = " + bestGame);
}   

}

【问题讨论】:

    标签: java variables methods static global


    【解决方案1】:

    如果你不能使用“全局”变量,我猜你唯一的选择是在调用方法时传递参数。如果你不知道如何声明和使用带参数的方法,我不知道另一个答案。

    编辑/添加

    在您指定您的问题、情况并发布您的代码后,我得到了一个可行的解决方案,包括 cmets。

    public class Guess {
        public static int MAXIMUM = 100;
    
        public static void main(String[] args) {
            boolean play = true; // true while we want to play, gets false when we quit
            int totalGuesses = 0; // how many guesses at all
            int bestGame = Integer.MAX_VALUE; // the best games gets the maximum value. so every game would be better than this
            int totalGames = 0; // how many games played in total
            Scanner console = new Scanner(System.in); // our scanner which we pass
    
            gameIntroduction(); // show the instructions
    
            while (play) { // while we want to play
                int lastGame = playGame(console); // run playGame(console) which returns the guesses needed in that round
                totalGames++; // We played a game, so we increase our counter
    
                if (lastGame < bestGame) bestGame = lastGame; // if we needed less guesses last round than in our best game we have a new bestgame
    
                totalGuesses += lastGame; // our last guesses are added to totalGuesses (totalGuesses += lastGame equals totalGuesses + totalGuesses + lastGame)
    
                play = checkPlayNextGame(console); // play saves if we want to play another round or not, whats "calculated" and returned by checkPlayNextGame(console)
            }
    
            getGameResults(totalGames, totalGuesses, bestGame); // print our final results when we are done
        }
    
        // Prints the instructions for the game.
        public static void gameIntroduction() {
            System.out.println("This process allows you to play a guessing game.");
            System.out.println("I will think of a number between 1 and");
            System.out.println(MAXIMUM + " and will allow you to guess until");
            System.out.println("you get it. For each guess, I will tell you");
            System.out.println("whether the right answer is higher or lower");
            System.out.println("than your guess.");
            System.out.println();
        }
    
        // Takes the user's input and compares it to a randomly selected number.
        public static int playGame(Scanner console) {
            int guesses = 0; // how many guesses we needed
            int guess = 0; // make it zero, so it cant be automatic correct
            System.out.println("I'm thinking of  a number between 1 and " + MAXIMUM + "...");
            int randomNumber = (int) (Math.random() * MAXIMUM + 1); // make our random number. we don't need the Random class with its object for that task
    
            while (guess != randomNumber) { // while the guess isnt the random number we ask for new guesses
                System.out.print("Your guess? ");
                guess = console.nextInt(); // read the guess
                guesses++; // increase guesses
    
                // check if the guess is lower or higher than the number
                if (randomNumber < guess) 
                    System.out.println("It's lower.");
                else if (randomNumber > guess) 
                    System.out.println("It's higher.");
            }
    
            System.out.println("You got it right in " + guesses + " guesses"); // Say how much guesses we needed
            return guesses; // this round is over, we return the number of guesses needed
        }
    
        public static boolean checkPlayNextGame(Scanner console) {
            // check if we want to play another round
            System.out.print("Do you want to play again? ");
            String input = (console.next()).toUpperCase(); // read the input
            if (input.contains("Y")) return true; // if the input contains Y return true: we want play another round (hint: don't use contains. use equals("yes") for example)
            else return false; // otherwise return false: we finished and dont want to play another round
        }
    
        // Prints the results of the game, in terms of the total number
        // of games, total guesses, average guesses per game and best game.
        public static void getGameResults(int totalGames, int totalGuesses, int bestGame) {
            // here you passed the total guesses twice. that isnt necessary.
            System.out.println("Overall results:");
            System.out.println("\ttotal games   = " + totalGames);
            System.out.println("\ttotal guesses = " + totalGuesses);
            System.out.println("\tguesses/games = " + ((double) (totalGuesses) / (double) (totalGames))); // cast the numbers to double to get a double result. not the best way, but it works :D
            System.out.println("\tbest game     = " + bestGame);
        }
    }
    

    希望我能帮上忙。

    【讨论】:

    • 我尝试在 playTest() 中调用 getGameResults() 以使用 playTest() 的局部变量,但该方法已在另一个方法中使用。现在,它不再打印在整个程序运行期间所有游戏中使用的所有猜测的总和,而是仅打印每个游戏期间的值。我不知道如何改变它。
    • 当你在方法 A 中调用方法 B 时,方法 B 无法访问 A 中的变量,除非你传递它们。但我想我没有明白这一点......你调用playGame(),它调用continuePlayTest(),它调用playGame() 还是getGameResults()。两者都再次调用 continuePlayTest()。对吗?
    • 对不起,我应该澄清一下。我将方法 A 中的变量作为方法 B 中的参数传递。是的,程序按照您的描述运行。
    • 看代码。你知道什么是 do-while-loop,你能让函数返回值吗?更容易找到解决方案。
    • 测试我在答案中添加的代码。它应该适合您的需求:D 不,我需要睡觉。现在是凌晨 3 点 22 分:D
    【解决方案2】:

    在函数之间传递变量是否有问题?例如:

    public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
        // implementation
    }
    

    另一种选择,假设这都在一个类中,是使用私有静态成员变量。它们不是全球性的。再说一次,你的老师可能会认为他们在这项作业中是“全球性的”。

    【讨论】:

    • 按照我老师的定义,它们被认为是全球性的,我们会因为使用它们而损失大量积分,这是我上周不幸发现的。
    • 如果我为这个程序发布了我的所有代码会有帮助吗?尝试使用 getGameResults 方法会产生其他错误。
    • 是的,更多上下文会有所帮助。
    【解决方案3】:

    鉴于您只学习了如何使用静态方法,您唯一的选择是通过参数在函数之间传递信息。

    【讨论】:

      猜你喜欢
      • 2013-11-28
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多