我正在编写一个用于学习目的的短代码,要求用户输入密码才能登录 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!");
}
}
上述脚本的几次运行:
Welcome to Facebook!
Enter your password : ksskasjaks
Congratulations, you have logged in to Facebook!
另一次运行:
Welcome to Facebook!
Enter your password : password
Congratulations, you have logged in to Facebook!
我排除了这样的情况,当然这里唯一的密码是“password”:
Welcome to Facebook!
Enter your password : ksskasjaks
Your password is incorrect. Try again!
Enter your password : password
Congratulations, you have logged in to Facebook!
知道为什么它没有按预期工作吗?谢谢。
最佳答案
使用 try catch:
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!");
}
关于java - Try-Catch 的 Catch 部分未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021988/