捕获部分Try-Catch没有执行

时间:2019-07-13 18:54:24

标签: java exception try-catch

我正在编写用于学习目的的短代码,要求用户输入密码以登录Facebook。我正在测试异常处理,由于某种原因,密码错误时 Catch 部分未执行。代码是:

import java.util.Scanner;

public class FacebookLogin {


    public static void printPassword() {
        Scanner sc = new Scanner(System.in);
        String password;

        try {

            System.out.print("Enter your password : ");
            password = sc.next();

        } catch (Exception x) {
            do {            
            System.out.println("Your password is incorrect. Try again!");
            System.out.print("Enter your password : ");
            sc.nextLine();
            password = sc.next();


            } while (password != "password");
        }
        sc.close();

    }

    public static void main(String[] args) {


        System.out.println("Welcome to Facebook!");

        printPassword();

        System.out.println("Congratulations, you have logged in to Facebook!");


    }

}

上面的脚本很少运行:

  

欢迎使用Facebook!

     

输入密码:ksskasjaks

     

恭喜,您已登录Facebook!

另一次跑步:

  

欢迎使用Facebook!

     

输入您的密码:密码

     

恭喜,您已登录Facebook!

我例外,例如,这里唯一的密码是“密码”:

  

欢迎使用Facebook!

     

输入密码:ksskasjaks

     

您的密码不正确。再试一次!

     

输入您的密码:密码

     

恭喜,您已登录Facebook!

任何线索为什么它没有按预期运行?谢谢。

2 个答案:

答案 0 :(得分:1)

尝试捕获:

 public static void enterPassword() throws Exception {
    Scanner sc = new Scanner(System.in);
    String password;
    System.out.print("Enter your password : ");
    password = sc.next();
    if (!password.equals("password")) {
        throw new Exception();
    }
}

public static void printPassword() {
    try {
        enterPassword();
    } catch (Exception e) {
        System.out.println("Your password is incorrect. Try again!");
        printPassword();
    }
}

public static void main(String[] args) {


    System.out.println("Welcome to Facebook!");

    printPassword();

    System.out.println("Congratulations, you have logged in to Facebook!");


}

答案 1 :(得分:0)

不需要尝试捕获,我想这就是您想要的:

public static void printPassword() {
    Scanner sc = new Scanner(System.in);
    String password;

    System.out.print("Enter your password : ");
    sc.nextLine();
    password = sc.next();
    while (!password.equals("password")) {
        System.out.println("Your password is incorrect. Try again!");
        System.out.print("Enter your password : ");
        sc.nextLine();
        password = sc.next();
    }

    sc.close();

}

public static void main(String[] args) {


    System.out.println("Welcome to Facebook!");

    printPassword();

    System.out.println("Congratulations, you have logged in to Facebook!");


}