Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
- Login simulation, give three chances, and prompts as well as several opportunities
- analysis:
-
A.定义两个字符串对象,用于储存已经存在的用户名和密码
-
B.键盘录入用户名和密码
-
C.拿键盘录入的用户名和密码和已经存在的用户名和密码进行比较
-
如果内容相同,提示登入成功
-
如果内容不同,提示登入失败,并提示还有几次机会
import java.util.Scanner;
public class StringTest {
public static void main(String[] args) {
//定义两个字符串对象
String username="admin";
String password="admin";
//给三次机会,用for循环实现
for(int x=0;x<3;x++) {//0,1,2
//键盘录入用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String name=sc.nextLine();
System.out.println("请输入密码:");
String pwd=sc.nextLine();
//拿键盘录入的用户名和密码和已经存在的用户名和密码进行比较
if(username.equals(name)&&password.equals(pwd)) {
System.out.println("登入成功");
break;
}else {
if((2-x)==0) {
System.out.println("用户名被锁定,请与管理员联系");
}else {
System.out.println("登入失败,你还有"+(2-x)+"次机会");//2,1,0
}
}
}
}
}