循环直到在java中输入零

时间:2014-05-13 05:42:54

标签: java eclipse

如果用户输入数字为零,我想从我的代码中停止

这是我的代码

public static void main(String[] args) {
    int choose_num =1;
    Functions fun = new Functions();
    while (choose_num != 0) {
        System.out.println("Hello My Friend, Please choose one: \n");
        System.out.println("1 for Calculator \n2 for compairing \n" +
                            "3 for calculate factorial\n" +
                            "0 for exit");
        Scanner in = new Scanner(System.in);
        try {
            choose_num = in.nextInt();
            switch (choose_num) {
            case 1: fun.add_two_number();
                break;
            case 2: fun.compaire();
                break;
            case 3: fun.factorial();
                break;
            default: choose_num = 0;
                break;
            }
        } finally {
            in.close();
        }
    }
}

第一次运行但是当它返回开始时我给出了错误

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at MyFirstProgram.main(MyFirstProgram.java:27)

我在ubuntu上使用eclipse请帮帮我

感谢

1 个答案:

答案 0 :(得分:5)

您过早关闭扫描仪。 删除in.close()行,或将其移至循环之外。