简体   繁体   English

使用Java中的Do-while循环的简单菜单

[英]Simple menus using Do-while loops in java

I am trying to make a simple menu using a do-while loop in java. 我正在尝试使用Java中的do-while循环制作一个简单的菜单。 My code looks like this: 我的代码如下所示:

int choice;
    Scanner scanChoice = new Scanner(System.in);
    do {
        System.out.println("Pick an option. 1 2 or 3.");
        System.out.println("1. Apple");
        System.out.println("2. Pear");
        System.out.println("3. Pineapple");

        choice = scanChoice.nextInt();
    } while (choice < 1 || choice > 3);

    System.out.println("You picked " + choice);

The problem is, every time I try to run it, it throws "java.util.NoSuchElementException". 问题是,每次我尝试运行它时,它都会引发“ java.util.NoSuchElementException”。 The full error is below: 完整错误如下:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at mainPackage.Main.fruitMenu(Main.java:135)
at mainPackage.Main.main(Main.java:103)

I know that this is because scanChoice.hasNextInt() returns false, but I'm not sure how to fix this. 我知道这是因为scanChoice.hasNextInt()返回false,但是我不确定如何解决此问题。 When I add an if statement ( if (scanChoice.hasNextInt()) ), the method scanChoice.hasNextInt() still returns false, so it just passes over the line that initializes the variable choice , and that variable never gets initialized. 当我添加一条if语句( if (scanChoice.hasNextInt()) ,方法scanChoice.hasNextInt()仍返回false,因此它仅经过初始化变量choice的那一行,并且该变量从未初始化。

Anyone know how to fix this? 有人知道怎么修这个东西吗?

EDIT: The problem is that it does not wait for the user to input another integer. 编辑:问题是它不等待用户输入另一个整数。 The function scanchoice.nextInt() , and the function scanChoice.nextLine() , both immediately return no value, without waiting for the user to input a value. 函数scanchoice.nextInt()和函数scanChoice.nextLine()都立即不返回任何值,而无需等待用户输入值。 Any way to make it wait for input? 有什么办法让它等待输入吗?

It seems to work for me, consistently. 它似乎一直对我有用。 For any valid integers it works as expected, either accepting the input or goes through a loop, and when typing invalid input like "abcd" it throws InputMismatchException , that is the expected behavior anyway. 对于任何有效的整数,它都可以按预期方式工作,无论是接受输入还是经过循环,当键入无效输入(如“ abcd”)时,它都会引发InputMismatchException ,无论如何这都是预期的行为。

Online Java compiler IDE 在线Java编译器IDE

I made your code more robust. 我使您的代码更加健壮。 It catches alphanumeric characters and displays the menu again, rather than abending with a InputMismatchException. 它捕获字母数字字符并再次显示菜单,而不是出现InputMismatchException异常。

Here's a test run. 这是一个测试运行。

Pick an option. 1 2 or 3.
1. Apple
2. Pear
3. Pineapple
x
Pick an option. 1 2 or 3.
1. Apple
2. Pear
3. Pineapple
asdf
Pick an option. 1 2 or 3.
1. Apple
2. Pear
3. Pineapple
2
You picked 2

And here's the code. 这是代码。 I called the Scanner nextLine method. 我称它为Scanner nextLine方法。

package com.ggl.testing;

import java.util.Scanner;

public class MenuTest {

    public static void main(String[] args) {
        int choice;
        Scanner scanChoice = new Scanner(System.in);

        do {
            System.out.println("Pick an option. 1 2 or 3.");
            System.out.println("1. Apple");
            System.out.println("2. Pear");
            System.out.println("3. Pineapple");

            String input = scanChoice.nextLine();
            choice = convertToInteger(input.trim());
        } while (choice < 1 || choice > 3);

        System.out.println("You picked " + choice);
        scanChoice.close();
    }

    private static int convertToInteger(String input) {
        try {
            return Integer.valueOf(input);
        } catch (NumberFormatException e) {
            return Integer.MIN_VALUE;
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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