调用另一个类时的NoSuchElementException

时间:2016-01-25 10:02:43

标签: java exception

我正在尝试编写一个游戏,您可以在其中搜索和查找资源,但是当我尝试调用"探索类"时,它会运行此代码:

Scanner scanner = new Scanner(System.in);
    int choose;
    boolean keep = false;
    do{
    System.out.println("Who would you like to send to explore?");
    System.out.println("=======================================");
    System.out.println(" *\t1. Simon                     *");
    System.out.println(" *\t2. Lily                      *");
    System.out.println(" *\t3. Axel                      *");
    System.out.println(" *\t4. Exit Exploring            *");
    System.out.println("=======================================");
    choose = scanner.nextInt();

返回主类并执行:

System.out.println("===================================");
        System.out.println("\t 1. Explore");
        System.out.println("\t 2. Use Resources");
        System.out.println("\t 3. View Stats");
        System.out.println("\t 4. Sleep");
        System.out.println("===================================");
        option = scanner.nextInt();//where I believe the exception happened

它抛出异常:java.util.NoSuchElementException

我在探索课结束时完成了scanner.close();,但我不确定是否会导致问题。

任何人都可以向我解释我的代码中的错误吗?

1 个答案:

答案 0 :(得分:0)

尝试使用

if(scanner.hasNextInt()){
    option = scanner.nextInt();
}