while循环执行一行代码两次

时间:2015-11-02 06:38:36

标签: while-loop java.util.scanner

这是我的代码。它是一个简单的控制台应用程序,旨在让我熟悉对象的使用。 `包okei; import java.util.Scanner;

公共课主 {

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

    Arg dec = new Arg();
    String answer = "";
    int howmuch;
    Boolean a = true;
    while(a)
    {   

        System.out.println("Drink, Fill, or Look?");
        answer = listen.nextLine();

        switch (answer)
        {
        case "Drink":
            System.out.println("How much?");
            howmuch = listen.nextInt();
            dec.drink(howmuch);
            break;
        case "Fill":
            System.out.println("How much?");
            howmuch = listen.nextInt();
            dec.fill(howmuch);
            break;
        case "Look":
            System.out.println(dec.look());
            break;
        case "Quit":
            listen.close();
            a=false;
            break;
        }

    }

}

} `

这是ouptut 喝酒,补酒还是看? 喝 多少? 10 喝酒,补酒还是看? 喝酒,补酒还是看?

为什么Drink,Fill或Look被执行两次?

1 个答案:

答案 0 :(得分:0)

只需将“answer = listen.nextLine()”更改为“answer = listen.next()”