首页 > 解决方案 > 调用方法后出现 NoSuchElement 异常

问题描述

对于一个类,我必须创建一个程序,该程序具有一个菜单,用户可以根据他们的选择从哪里选择它运行某些方法。我遇到的问题是在我调用我的方法之后,程序在第 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

标签: javadebuggingmethodsvoid

解决方案


if(console.hasNextInt()){
  selection = console.nextInt();
}

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


推荐阅读