[英]Catch part of Try-Catch not executing
我正在编写用于学习目的的短代码,要求用户输入密码以登录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!
有什么线索为什么它没有按预期工作? 谢谢。
使用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!");
}
无需尝试捕获,我想这就是您想要的:
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!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.