繁体   English   中英

在其他静态方法中调用局部变量?

[英]Calling local variables in other static methods?

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

将打印这些结果。 负责运行游戏的功能(playGame())和负责打印这些结果的功能(getGameResults())必须使用两种单独的方法。

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

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

我们只能使用我们学到的概念。 我们不能在前面使用任何概念。 到目前为止,我们已经学习了如何使用静态方法,循环,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);
}   

}

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

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

假设所有这些都在一个类中,则另一种选择是使用私有静态成员变量。 他们不是全球性的。 再说一遍,您的老师可能会将其视为“全局”作业。

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

编辑/添加

在指定问题,情况并发布代码后,我得到了一个有效的解决方案,包括注释。

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);
    }
}

希望我能帮上忙。

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

暂无
暂无

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

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