【案例5-3】 模拟用户登录
【案例介绍】
1.任务描述
在使用一些APP时,通常都需要填写用户名和密码。用户名和密码输入都正确才会登录成功,否则会提示用户名或密码错误。
本例要求编写一个程序,模拟用户登录。程序要求如下:
(1) 用户名和密码正确,提示登录成功。
(2) 用户名或密码不正确,提示“用户名或密码错误”。
(3) 总共有3次登录机会,在3次内(包含三次)输入正确的用户名和密码后给出登录成功的相应提示。超过3次用户名或密码输入有误,则提示登录失败,无法再继续登录。。
在登录时,需要比较用户输入的用户名密码与已知的用户名密码是否相同,本案例可以使用Scanner类以及String类的相关方法实现比较操作。
package com.j2se.myInstances.example5_3;
import java.util.Scanner;
public class UserLogin {
private static String[] arr1 = new String[5];
private static String[] arr2 = new String[5];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
arr1[0] = "James";
arr2[0] = "James23";
int count = 3;
System.out.println("总共3次登录机会,您还有" + count + "次机会");
for (int i = 0; i < 3; i++) {
System.out.println("用户名:");
String uname = sc.nextLine();
System.out.println("密码:");
String upasswd = sc.nextLine();
if (uname.equals(arr1[i]) && upasswd.equals(arr2[i])) {
System.out.println("登录成功!");
break;
} else {
count--;
if (count == 0) {
System.out.println("3次登录失败,账户已锁定");
} else {
System.out.println("用户名或密码错误,请重新输入!");
System.out.println("总共3次登录机会,您还有" + count + "次机会");
}
}
}
}
}