I have a menu for a Bank in the main class the Scanner is initialized in the irrelevant above code
Main
while(true) {
Scanner kbs = new Scanner(System.in);
try {
Menu.mainMenu();
int selection = kbs.nextInt();
try {
if(selection == 1) {
dublin.customerWithdraw();
}
else if(selection == 0) {
break;
}
}
catch(NoSuchElementException e) {
System.out.println("That is not a option");
}
}
catch(InputMismatchException e) {
System.out.println("That is not a option");
}
}
The `dublin.customerWithdraw(); calls a method in bank which also uses a Scanner
Bank
//Customer Withdraw
public void customerWithdraw() {
Scanner kb = new Scanner(System.in);
//List of Customers to choose from
//Selecting the Id of Customer
//Finding the Customer from the ArrayList
viewCustomers();
System.out.println("Enter Customers Passport Number:");
String custPastport = kb.nextLine();
Customer customerFind = findCustomer(custPastport);
if(customerFind != null){
//Check to make sure the amount entered for the withdraw request is valid
try {
//Calling Customer scanArmChip method to scan composed ArmChip Id
// if they are correct proceed with withdraw
if(customerFind.scanID()) {
System.out.println("Enter withdraw amount: ");
int withdraw = kb.nextInt();
//Calling the Customer withdraw method to minus the wanted amount
customerFind.withdraw(withdraw);
System.out.println(customerFind);
}
else {
System.out.println("Person Id does not match Arm Id call police!!!");
}
}
catch(NullPointerException e){
System.out.println("This ID is not valid");
}
}
else {
System.out.println("The passport number entered is incorrect");
}
//If I close the scanner here I get a error
}
The error message displayed is
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:51)
I have done some research and found out that because I close the Scanner in the infinite loop it can not reopen even if I close it in the outside method.
I need to have it closeed in both classes and im not sure how?
The Menu works fine and executes the methods when I just choose not to close the Scanner object and the loop will present the user with the option to choose again.
If I close the object in the Main
class or in the Bank
class that is when I get the error.