今天学的登录访问代码,和前天学的猜数字小游戏结合在一起,但是有点不足,后来想到for循环中的break的标记法,问题马上解决了。- import java.util.Random;
- import java.util.Scanner;
- public class LoginTest {
- public static void main(String[] args) {
- //创建对象
- User user = new User();
- user.setUserName("maxilong");
- user.setUserPassword("12345");
-
- w: for (int x = 0; x < 3; x++) {
- //获取键盘录入
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入用户名:");
- String name = sc.nextLine();
- System.out.println("请输入密码:");
- String pwd = sc.nextLine();
- //判断用户名和密码是否正确
- if (user.isLogin(name, pwd)) {
- System.out.println("恭喜您登陆成功!");
- int i = 100;
- //创建Random类并调用对象
- Random r = new Random();
- int y = r.nextInt(i);
- while (true) {
- Scanner sc1 = new Scanner(System.in);
- System.out.println("请您输入一个数(1-100)——猜数字游戏开始:");
- int num = sc1.nextInt();
- if (num > y) {
- System.out.println("您猜的数" + num + "大了,再猜猜看!");
- } else if (num < y) {
- System.out.println("您猜的数" + num + "小了,再猜猜看!");
- } else {
- System.out.println("恭喜您,猜对了,大神...");
- //跳出标记的循环
- break w;
- }
- }
- } else {
- if ((2 - x) == 0) {
- System.out.println("用户已被锁定,请与管理员联系!");
- break;
- }
- System.out.println("用户名或密码不正确,请重新输入,您的登录次数还有" + (2 - x) + "次!");
- }
- }
- }
- }
- public class User {
- private String userName;
- private String userPassword;
- public User() {
- super();
- // TODO Auto-generated constructor stub
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getUserPassword() {
- return userPassword;
- }
- public void setUserPassword(String userPassword) {
- this.userPassword = userPassword;
- }
- /**
- *
- * @param name
- * 用户名
- * @param password
- * 密码
- * @return 用户登录是否成功
- */
- public boolean isLogin(String userName, String userPassword) {
- return this.userName.equals(userName)
- && this.userPassword.equals(userPassword);
- }
- }
复制代码 :) |
|