簡體   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