I want to create a static scanner but i will like to put the try catch block around it so it can automatically close avoiding resources leaks and or this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at softwareEngineer.UserApp1.main(UserApp1.java:82)
Essentially I only want to create one static scanner declaration and use it throughout the main program and includes the static methods, at this point my code will require to create separate scanner for each method and you are force "scan.close()". the code below will recieve a exception handling error due to multiple scanner that was open and did not closein the program.
I updated the code now i get null pointer exception
import java.util.Scanner;
public class UserApp1 {
static User currentCustomer = null; //single object
static Scanner scan;
//-------------------------------------------------------
// Create a list, then repeatedly print the menu and do what the
// user asks until they quit
//-------------------------------------------------------
public static void main(String[] args) {
scan = new Scanner(System.in);)//scanner to avoid resource leak
printMenu(); //print menu system from another function
String choice = scan.nextLine(); //reads an input
final String EXIT_now = "0";
final String BACK = "back";
while (!(choice.equalsIgnoreCase(EXIT_now))){
switch(choice) {
case 1: break;
case 2:
currentCustomer = loginInput();<---- errors happens here
if(currentCustomer != null){
System.out.println("You have successfully login");
}
break;
default:
System.out.println("Sorry, invalid choice");
break;
} //ends switch
printMenu(); //print menu system from another function
choice = scan.nextLine(); //reads an input
}//ends while
System.out.println("\t\t GoodBye!\n Thank you for trying our program.");
System.exit(0);
}//ends main
//----------------------------
// Print the user's choices
//----------------------------
public static void printMenu() {
System.out.println("\t\t The User Login System ");
System.out.println("\t\t ======================");
System.out.println("The Menu Options:");
System.out.println("1: Register an Account");
System.out.println("2: Login to your Account");
System.out.println("3: Reset Password");
System.out.println("0: Quit/Exit ");
System.out.println("Please enter your selection > ");
} //ends printMenu
public static User loginInput(){
System.out.print( "\nFollow the Prompts to Log-In to your Account \n ");
System.out.print( "\nPlease enter your userid : \n ");
String userid = scan.nextLine();// <---- errors happens here
System.out.print( "\nPlease enter your password: \n ");
String pass = scan.nextLine();
currentCustomer = AccountList.loginUser(userid, pass);
if (currentCustomer != null)
{
return currentCustomer;
}
return null;
}//ends loginInput
}//ends class*