简体   繁体   中英

NoSuchElement exception after calling a method

For a class I have to create a program that has a menu that users can pick from where depending on their choice it runs certain methods. The issue I am having is after I call my methods, the program throws a NoSuchElement exception on line 30 (26 when I have the code pasted below, it's the line where it says selection = console.nextInt()) when it should be allowing the user to select an option from the menu again. Any idea why this is happening anyone?

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
if(console.hasNextInt()){
  selection = console.nextInt();
}

hasNextInt() will make sure that there is an in integer to read from stream before reading it using nextInt(). If not, you may get a NoSuchElementException if stream is already exhausted.

@StefanR was right in that it was the closing of my scanner that caused the issue. Moving the scanner into the class field threw an error, but simply removing the console.close() from my methods fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM