有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用I/O在Java中设置循环菜单

我在尝试用Java设置一个简单的菜单并将其输出到文件时遇到了一个问题。当我使用菜单选项“1”运行此程序时我得到了链接中看到的输出Output

public static void main(String args[])
          throws FileNotFoundException{
            PrintStream output = new PrintStream( new File("hello.txt")); // created 
            Scanner keyboard = new Scanner(System.in);

            System.out.println("1. favorite pie");
            System.out.println("2. favorite tv show");
            System.out.println("3. favorite number");
            System.out.println("Enter your choice: ");

            int selection = keyboard.nextInt(); // is javadoc comment precondiiton sufficient here?



             while (!keyboard.hasNextInt()){
                System.out.println("Input an integer"); 
                selection = keyboard.nextInt(); //if user puts in double will an error be thrown?
            }


            if (selection ==1){
                System.out.println("What is your favorite pie?");
                String favoriteFood = keyboard.nextLine();
                System.out.println("Your favorite pie is" + favoriteFood);
                output.println(favoriteFood);
            }
            else if(selection ==2){
                System.out.println("What is your favorite tv show?");
                String tvFood = keyboard.nextLine();
                System.out.println(tvFood);
                output.println(tvFood);
            }
            else if (selection == 3){
                System.out.println("what is your favorite number?");
                String num = keyboard.nextLine();
                System.out.println(num);
                output.println(num);
            }
      }

共 (1) 个答案

  1. # 1 楼答案

    这是因为您在从流中接收到整数后调用hasNextInt

    由于调用hasNextInt,程序必须等待控制台的更多输入,才能知道是否还有另一个整数

    一旦hasNextInt开始返回false,它在未来将永远不会再次为true,因为整个输入流都已被读取和关闭,因此保持while循环以检查输入是没有意义的。只需移除回路,保持以下位置:

    int selection = keyboard.nextInt();