2

我遇到了一个问题,即 Scanner 在无限期的 while 循环中没有阻止用户输入。我试过使用hasNextLine(),但没有奏效。它只是无限地运行循环调用displayMenu().

     do {

        displayMenu();

        int response;
        while (iStream.hasNextLine()) {
            response = Integer.parseInt(iStream.nextLine());

            switch (response) {
                case 1:
                    decodeMessage(getPhrase());
                    break;
                case 2:
                    encodeMessage(getPhrase());
                    break;
                case 3:
                    displayAlphabet();
                    break;
                case 4:
                    done = true;
                    System.out.println("Goodbye.");
                    break;
                default:
                    done = false;
            }
        }

    }
    while (!done);

我也尝试过不使用hasNextLine(),但我最终得到了 a NoSuchElementException,因为它第一次完美运行,但在第二次迭代中,它不会阻止用户输入。

    do {

        displayMenu();

        int response = Integer.parseInt(iStream.nextLine());

            switch (response) {
                case 1:
                    decodeMessage(getPhrase());
                    break;
                case 2:
                    encodeMessage(getPhrase());
                    break;
                case 3:
                    displayAlphabet();
                    break;
                case 4:
                    done = true;
                    System.out.println("Goodbye.");
                    break;
                default:
                    done = false;

        }

    }
    while (!done);

有什么想法吗?

4

1 回答 1

0

以下对我来说很好:

private static void displayMenu ()
{
    System.out.println ("Menu:");
    System.out.println ("\t1: Decode message");
    System.out.println ("\t2: Encode message");
    System.out.println ("\t3: Display alphabet");
    System.out.println ("\t4: Exit");
}

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

    boolean done = false;
    while (!done)
    {
        displayMenu();

        switch (Integer.parseInt (scanner.nextLine ()))
        {
            case 1:
                System.out.println ("Decoding...");
                break;
            case 2:
                System.out.println ("Encoding...");
                break;
            case 3:
                System.out.println ("Displaying alphabet...");
                break;
            case 4:
                System.out.println("Exitting...");
                done = true;
                break;
            default:
                done = false;
        }
    }
}
于 2013-02-09T16:39:25.097 回答