繁体   English   中英

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

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

我正在尝试使用Java中的do-while循环制作一个简单的菜单。 我的代码如下所示:

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

问题是,每次我尝试运行它时,它都会引发“ java.util.NoSuchElementException”。 完整错误如下:

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)

我知道这是因为scanChoice.hasNextInt()返回false,但是我不确定如何解决此问题。 当我添加一条if语句( if (scanChoice.hasNextInt()) ,方法scanChoice.hasNextInt()仍返回false,因此它仅经过初始化变量choice的那一行,并且该变量从未初始化。

有人知道怎么修这个东西吗?

编辑:问题是它不等待用户输入另一个整数。 函数scanchoice.nextInt()和函数scanChoice.nextLine()都立即不返回任何值,而无需等待用户输入值。 有什么办法让它等待输入吗?

它似乎一直对我有用。 对于任何有效的整数,它都可以按预期方式工作,无论是接受输入还是经过循环,当键入无效输入(如“ abcd”)时,它都会引发InputMismatchException ,无论如何这都是预期的行为。

在线Java编译器IDE

我使您的代码更加健壮。 它捕获字母数字字符并再次显示菜单,而不是出现InputMismatchException异常。

这是一个测试运行。

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

这是代码。 我称它为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