一,利用Scanner创建一个猜数字游戏
先在主方法创建一个随机数,然后创建一个while循环不断获取用户输入的数字,让用户输入的数字与随机数比较,给出相应的提醒,直到输入正确为止。
public class Demo { public static void main(String[] args) { Random r = new Random(); int num = r.nextInt(100);// 从1~99取值 int input = -1;// 记录用户输入的值 Scanner sc = new Scanner(System.in); while (true) { System.out.println("猜一猜随机数是多少?"); input = sc.nextInt(); if (input > num) { System.out.print("你输入的数字大了! "); } else if (input < num) { System.out.print("你输入的数字小了! "); } else if (input == num) { break; } else { System.out.println("您的输入有误! "); } } System.out.println("恭喜你答对了!"); } }
二,利用Scanner创建一个用户登录,并且循环几次之后结束
public class Demo{ public static void main(String[] args) { String username = "yy"; String password = "115"; for (int i = 1; i <= 3; i++) { Scanner sc = new Scanner(System.in); System.out.println("输入你的用户名"); String uname = sc.nextLine(); System.out.println("输入你的密码"); String pwd = sc.nextLine(); if (uname.equals(username) && pwd.equals(password)) { System.out.println("登陆成功"); break; } else { if (i == 3) { System.out.println("次数用完"); } else { System.out.println("你输入的密码错误,请重新输入,剩余次数为" + (3 - i) + "次"); } } } sc.close(); } }