In the below code I have used two scanners, One in performAction() method and one in getTicketNumber() method. I have used try with resources and once when I go into getTicketNumber() method, it works fine and once when the control returns back and comes to performAction() I am getting No Such Element Exception when it executes the scanner.nextInt() line. I wanted to continue this process until I press exit. I guess it is due to the use of multiple scanners since if I don't go into getTicketNumber() method, it works fine. Any ideas?
private void performAction() {
int choice = 4;
System.out.println("Hi User");
System.out.println("What do you want to do ");
try (Scanner scanner = new Scanner(System.in)) {
do {
System.out.println("1. Book ticket");
System.out.println("2. Cancel ticket");
System.out.println("3. Check status");
System.out.println("4. Exit");
System.out.println("Enter your choice");
choice = scanner.nextInt();
System.out.println();
doActionBasedOnChoice(choice);
System.out.println();
} while (choice != 4);
} catch (InputMismatchException e) {
System.out.println("Please enter a valid choice");
}
}
private void doActionBasedOnChoice(int choice) {
switch (choice) {
case 1:
ticketReservation.bookFlight();
break;
case 2:
System.out.println("Please enter your ticket number ");
int ticketNumber = getTicketNumber();
ticketReservation.cancel(ticketNumber);
break;
case 3:
ticketReservation.checkConfirmedListStatus();
break;
case 4:
System.out.println("Thank you ");
break;
default:
break;
}
}
private int getTicketNumber() {
try (Scanner scanner = new Scanner(System.in)) {
int choice = scanner.nextInt();
return choice;
} catch (InputMismatchException e) {
System.out.println("Please enter a valid ticekt number");
}
return 0;
}