题目内容
编写代码模拟三次密码输入的场景。 最多能输入三次密码,密码正确,提示“登录成功”,密码错误, 可以重新输 入,最多输入三次。三次均错,则提示退出程序
代码
首先给定账号和密码
String account="zouyi";
String password="jia123hui";
然后开始输入,首先输入账号,然后用equals()方法比较,如果对了,进入循环输入密码,如果错了,提示输入错误,重新输入。
while(true) {
System.out.print("account:");
Scanner sc=new Scanner(System.in);
String s1=sc.next();
如果账号正确,进入循环比较密码。
if (s1.equals(account)) {
int i = 0;
while (i < 3) {
System.out.print("password:");
String s2 = sc.next();
if (s2.equals(password)) {
System.out.println("Login successful");
break;
} else {
if(i==2){
System.out.println("Exit program!");
break;
}
else {
System.out.println("Incorrect input,Please re-enter!");
}
}
i++;
}
break;
}
最后的break不能省略!
总代码
public static void main(String[] args) {
String account="zouyi";
String password="jia123hui";
while(true) {
System.out.print("account:");
Scanner sc=new Scanner(System.in);
String s1=sc.next();
if (s1.equals(account)) {
int i = 0;
while (i < 3) {
System.out.print("password:");
String s2 = sc.next();
if (s2.equals(password)) {
System.out.println("Login successful");
break;
} else {
if(i==2){
System.out.println("Exit program!");
break;
}
else {
System.out.println("Incorrect input,Please re-enter!");
}
}
i++;
}
break;
}
}
}
运行结果