Java experiment topic: Simulate user login. Write a program to simulate user login.
The program requirements are as follows :
(1) If the user name and password are correct (case-insensitive), it will prompt "Successful login" and open the Windows calculator program; (2) If the user
name or password is incorrect, it will prompt "User name or password error";
(3 ) There are a total of 3 login opportunities, if more than 3 times, it will prompt "login failed, cannot continue to log in".
内联代码片
package Text;
import java.util.Scanner;
public class S5_2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
//定义变量记录正确的用户名和密码
String rightUsername = "zhang";//正确的用户名
String rightPassword = "123";//正确密码
for (int i=0;i<3;i++) {
//i 0,1,2
//键盘输入
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.next();
System.out.println("请输入密码:");
String password = sc.next();
//字符串比较equals
if(username.equals(rightUsername) && password.equals(rightPassword)) {
System.out.println("登陆成功!");
break;
}else
if(i==2){
//最后一次机会用完
System.out.println("登陆失败,3次机会已用完,无法继续登录!");
}else{
System.out.println("登陆失败,用户名或密码有误!还有"+(2-i)+"次机会!");
}
}
}
}
Experimental results: