On my previous question I've learned that I shouldn't close the System.in
, and I also learned that using multiple Scanner
together can cause problems.
The problem is that I need some methods recursively to use the Scanner
to scan some inputs from the user.
Example
public void usersChoice(){
int choice = 0;
while(true){
try{
Scanner scan = new Scanner(System.in);
System.out.print("Choose an option: ");
choice = scan.nextInt();
break;
}
catch(Exception e){
System.out.println("Invalid Input!\n");
}
}
switch (choice){
case 1:
choiceNewAccount();
break;
case 2:
choiceLogin();
break;
case 3:
choiceRemoveAccount();
break;
case 4:
exit();
break;
default:
System.out.println("Invalid Input!\n");
break;
}
Case 1:
public void createAccount(){
try{
Scanner scan = new Scanner(System.in);
System.out.print("Enter Your Username: ");
String username = scan.next();
if(!isValidUsername(username)) System.out.println("Username Already Exists!");
else{
while(true){
System.out.print("Enter Your Password: ");
String pass1 = scan.next();
System.out.print("Re-Enter Your Passowrd: ");
String pass2 = scan.next();
if(!arePasswordsMatch(pass1,pass2)) System.out.println("Passowrds Don't Match!");
else {
addToAccountsList(username,pass1);
createTheUsersFile(username);
System.out.println("The Account Has Been Successfully Created!");
break;
}
}
}
} catch(Exception e){
System.out.println("Could Not Create Account!");
}
Do I need to create one System.in Object and use it on my whole program? Or is there an other way to work with the System.in Object?