java案例5-3用户登录一共有三次机会
时间: 2024-02-09 20:10:34 浏览: 24
好的,那么我可以为您提供一个带有三次登录机会的Java用户登录案例,代码如下所示:
```java
import java.util.Scanner;
public class UserLogin {
public static void main(String[] args) {
String username = "admin";
String password = "123456";
Scanner sc = new Scanner(System.in);
int count = 3; // 设置登录次数
while(count > 0) { // 循环判断登录次数是否大于0
System.out.print("请输入用户名:");
String inputName = sc.next();
System.out.print("请输入密码:");
String inputPwd = sc.next();
if (username.equals(inputName) && password.equals(inputPwd)) {
System.out.println("登录成功!");
break; // 登录成功,跳出循环
} else {
count--; // 登录失败,次数减1
System.out.println("用户名或密码错误!您还剩" + count + "次机会!");
}
}
if(count == 0) { // 登录次数用尽,提示用户并退出程序
System.out.println("您的登录次数已用尽,请稍后再试!");
System.exit(0);
}
}
}
```
这个程序在原有的基础上增加了一个计数器count,初始值为3,表示用户最多可以尝试登录3次,如果在三次内登录成功,则跳出循环,否则提示用户登录次数已用尽并退出程序。