java - 我使用 Java 制作的菜单中的无限循环

标签 java loops menu switch-statement

这是相关的代码。我有一个 switch 语句,以便用户可以在打印出来的给定选项之间输入他们的选择。当我输入 2、3 或任何其他数字时,它工作正常。但是一旦我选择第一个选项(玩游戏),它就会转到该方法并正常工作。但是,一旦方法结束并且大小写中断,编译器将返回到 while 循环的顶部,并且不会让用户选择其他选项。相反,它会再次选择第一个选项并继续这个无限循环。我该如何解决这个问题?

package rockPaperScissors;

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {

    public static void main(String[] args) {

        System.out.println("Welcome to Rock Paper Scissors!");

        Scores scores = new Scores(); //Object that holds two integers and allows you to increment them
        Scanner playerChoice = new Scanner(System.in);
        int option = 0;

        do{

            System.out.println("Select an option!");
            System.out.println("1: Play the game");
            System.out.println("2: Check the score");
            System.out.println("3: Quit the game");

            option = playerChoice.nextInt(); /*Shouldn't this line stop and let me
                                             enter another option for the menu? */

            switch(option) {

                case 1: playGame(scores);
                        break;

                case 2: getScore(scores);
                        break;

                case 3: System.out.println("Thanks for playing!");
                        break;

                 default: System.out.println("You must pick one of given options\n");
                          break;
            }


        } while(option != 3);

        playerChoice.close();

    }

我觉得奇怪的是,这里的这段代码完全按照我想要的方式工作,但它们本质上是相同的:

import java.util.Scanner;

public class Menu {

    public static void main(String[] args) {

        System.out.println("Welcome to a simple menu that does nothing!\n");
        Scanner input = new Scanner(System.in);

        int menuChoice;

        do{

            System.out.println("Please select an option!\n");

            System.out.println("1: This does nothing");
            System.out.println("2: This also does nothing");
            System.out.println("3: You guessed it, it does nothing");
            System.out.println("4: Quit\n");

            menuChoice = input.nextInt();

            switch(menuChoice){

                case 1: System.out.println("You chose option 1");
                        break;

                case 2: System.out.println("You chose option 2");
                        break;

                case 3: System.out.println("You chose option 3");
                        break;

                case 4: System.out.println("Goodbye!");
                        break;

                default: System.out.println("ENTER A VALID INPUT");
            }

        }while(menuChoice != 4);

        input.close();

    }

}

编辑:

所以 playGame 是一个实际处理游戏中石头剪刀布部分的方法。

private static Scores playGame(Scores scores) {

    System.out.println("Pick either rock, paper, or scissors");

    //The player makes a choice
    Scanner scanner = new Scanner(System.in);
    String playerDecision = "";

    if(scanner.hasNextLine()){
        playerDecision = scanner.nextLine(); 
    }


    //Check to see if the player chose one of the given options
    if(playerDecision.equalsIgnoreCase("rock") == false && playerDecision.equalsIgnoreCase("paper") == false && playerDecision.equalsIgnoreCase("scissors") == false){

        System.out.println("You must select either rock, paper, or scissors");
        scanner.close();
        return scores;
    }

    //The computer makes a random choice
    Random random = new Random();
    String gameArray[] = {"rock", "paper", "scissors"};
    int randNum = random.nextInt(3);
    String computerChoice = gameArray[randNum];

    System.out.println("You chose: " + playerDecision + "\nThe computer choice: " + computerChoice);


    if(playerDecision.equalsIgnoreCase(computerChoice)){ //If it's a tie

        System.out.println("It's a tie!");
        scanner.close();
        return scores;

    } else if(playerDecision.equalsIgnoreCase("rock")){ //If the player chooses rock

        if(computerChoice.equalsIgnoreCase("paper")){ //If the computer chooses paper
            System.out.println("The computer wins!");
            scores.incrementComputerScore();
            scanner.close();
            return scores;

        } else if(computerChoice.equalsIgnoreCase("scissors")){ //If the computer chooses scissors
            System.out.println("You win!");
            scores.incrementPlayerScore();
            scanner.close();
            return scores;
        }

    } else if(playerDecision.equalsIgnoreCase("paper")){ //If the player chooses paper

        if(computerChoice.equalsIgnoreCase("rock")){ //If the computer chooses rock
            System.out.println("You win!");
            scores.incrementPlayerScore();
            scanner.close();
            return scores;

        }else if(computerChoice.equalsIgnoreCase("scissors")){ //If the computer chooses scissor
            System.out.println("The computer wins!");
            scores.incrementComputerScore();
            scanner.close();
            return scores;
        }

    } else if(playerDecision.equalsIgnoreCase("scissors")){ //If the player chooses scissors

        if(computerChoice.equalsIgnoreCase("rock")){ //If the computer chooses rock
            System.out.println("The computer wins!");
            scores.incrementComputerScore();
            scanner.close();
            return scores;

        }else if(computerChoice.equalsIgnoreCase("paper")){ //If the computer chooses paper
            System.out.println("You win!");
            scores.incrementPlayerScore();
            scanner.close();
            return scores;
        }
    }
    scanner.close();
    return scores;

}

最佳答案

您将在 playgame() 方法中关闭扫描器,通过关闭扫描器,您还关闭了用于构造它的输入流。 Scanner.close() 的 javadoc 中对此进行了解释

由于程序的输入流现已关闭,您的主循环将不会返回 scanner.nextInt() 的任何有意义的完整信息(hasNextInt()现在将返回 false)并且由于扫描仪的当前实现,它将返回最后一个有效值。

要解决该问题,您可以使用多种解决方案。

通过扫描仪玩游戏(推荐)

通过向接受原始扫描仪的 playgame 添加参数,可以防止它需要在 playgame 主体内关闭

public void playGame(Score scores, Scanner scan) { // change arguments of constructor
  ....
  // scanner.close() // Drop this line too
}

未关闭游戏内的扫描仪 还有另一种方法可以解决这个问题,那就是不关闭 playgame 方法内的扫描仪,但是不建议这样做,因为扫描仪可能会在流上预读并消耗针对主菜单的字节,这个问题是对于您的用户交互用例来说并不是很大。

关于java - 我使用 Java 制作的菜单中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32290388/

相关文章:

java - 将大量字符串加载到我的 ArrayList 中,我不想阻塞我的类(class)

python - 无法将循环限制为 21 行

html - 隐藏在幻灯片后面的下拉菜单

python - 列表列表之间的最短路径

javascript - 在我的猜数游戏中遇到 while 循环问题

Android:对话框立即消失

android - 10 英寸平板电脑上的偏好菜单

java - NoSuchMethodError com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap$Builder.maximumWeightedCapacity

java - 删除节点的所有子节点,同时保留对 Firebase 中父节点的引用

java - 参数化对象无法解析为变量