简体   繁体   中英

Calling local variables in other static methods?

I am supposed to write a program that selects a random number between user given constraints, and asks the user to input guesses as to what this number is. The program gives feedback to the user as to whether or not the number is higher or lower than the user's guesses. The number of guesses, the number of games, the total guesses used throughout all of the games, and the lowest number of guesses used in one game are recorded.

These results are printed. The functions that responsible for running the game (playGame()) and the functions responsible for printing these results (getGameResults()) must be in two separate methods.

My problem is, I am not sure how to get the local variables that are modified throughout the course of the method playGame() to the getGameResults() method.

getGameResults() is intended to be called in another method, continuePlayTest(), which tests the user's input to determine whether or not they wish to continue playing the game, so I don't think that calling getGameResults() will work, otherwise this test will not work either. Unless I call continuePlayTest() in playGame(), but continuePlayTest() calls playGame() in its code so that would complicate things.

We can use ONLY the concepts that we've learned. We cannot use any concepts ahead. So far, we've learned how to use static methods, for loops, while loops, if/else statements and variables. Global variables are bad style, so they cannot be used.

CODE:

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

}

Is it a problem passing the variables between functions? ex:

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

Another option, assuming this is all in one class, is using private static memeber variables. They aren't global. Then again, they might be considered 'global' by your teacher for this assignment.

If you cannot use "global" variables, I guess your only option is passing parameters when calling the method. If you don't know how to declare and use methods with parameters, I don't know another answer.

EDIT/ADD

After you specified your question, circumstances and posted your code I got a working solution including comments.

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

Hope I could help.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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