1

在我之前的问题中,我了解到我不应该关闭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 对象?

4

0 回答 0