在我之前的question我已经了解到我不应该关闭System.in
,而且我还了解到同时使用多个Scanner
会导致问题。
问题是我需要一些递归的方法来使用Scanner
来扫描用户的一些输入。
示例
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;
}
案例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!");
}
我是否需要创建一个System.in对象并在整个程序中使用它?或者是否有另一种方法可以使用System.in对象?