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

时间:2014-10-28 23:49:56

标签: java variables methods static global

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

打印出这些结果。负责运行游戏的函数(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);
}   

}

3 个答案:

答案 0 :(得分:0)

在函数之间传递变量是一个问题吗?例如:

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

另一个选项,假设这是一个类,使用私有静态memeber变量。他们不是全球性的。然后,您的老师可能会认为这些任务可能会“全球化”。

答案 1 :(得分:0)

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

修改/添加

在您指定了问题,情况并发布了代码后,我得到了一个包含评论的工作解决方案。

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

希望我能提供帮助。

答案 2 :(得分:0)

鉴于您只学会了如何使用静态方法,您唯一的选择是通过其参数将信息从函数传递给函数。