【问题标题】:NoSuchElement exception after calling a method调用方法后出现 NoSuchElement 异常
【发布时间】:2018-11-03 15:45:39
【问题描述】:

对于一个类,我必须创建一个程序,该程序有一个菜单,用户可以根据他们的选择从哪里选择它运行某些方法。我遇到的问题是在我调用我的方法之后,程序在第 30 行抛出 NoSuchElement 异常(当我在下面粘贴代码时,它是第 26 行,当它应该允许时它显示 selection = console.nextInt())用户再次从菜单中选择一个选项。知道为什么会发生这种情况吗?

import java.util.*;
public class PartB {

public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    String pinNum;
    int selection = 0;
    boolean pin;

    System.out.print("Enter pin: ");

    pinNum = console.next();

    pin = check_pin(pinNum);

    if (pin == false) {
        System.out.print("Thank you for using the menu system. Goodbye");
    }


        while (selection != 4 && pin==true) {

        System.out.printf("%nPlease select a number from the menu below %n1: Wage "
            + "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");

        selection = console.nextInt();

        if (selection == 1) {
            calc_wages();
        } else if (selection == 2) {
            calc_tip();
        } else if (selection == 3) {
            System.out.print("We haven't gotten this far yet");
        } else if (selection == 4){
            System.out.print("Thank you for using the program.");
            break;
        } else {
            System.out.print("There is no option for what you entered. Try again");
        }
            selection = 0;
        }

    console.close();
}//main

【问题讨论】:

  • 我猜你在你的一个方法中使用了 Scanner(System.in) 并在那里关闭它,这将完全关闭你的应用程序的标准输入,所以你在主循环中的扫描仪将抛出 NoSuchElementException。也许将扫描仪变量移动到类字段并在所有方法中使用相同的实例。

标签: java debugging methods void


【解决方案1】:
if(console.hasNextInt()){
  selection = console.nextInt();
}

hasNextInt() 将确保在使用 nextInt() 读取流之前从流中读取整数。如果没有,如果流已经用尽,您可能会收到 NoSuchElementException。

【讨论】:

  • 这会导致无限循环,因为它一直提示直到输入一个数字,而不是提示一次。
【解决方案2】:

@StefanR 是正确的,因为我的扫描仪关闭导致了这个问题。将扫描仪移到类字段中会引发错误,但只需从我的方法中删除 console.close() 即可解决问题。

【讨论】:

    猜你喜欢
    • 2013-12-29
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多