需求:模拟登录,给三次机会,并提示还有几次。
用户名和密码都是admin
分析:
1,模拟登录,需要键盘录入,Scanner
2,给三次机会,需要循环,for
3,并提示有几次,需要判断,if
1 import java.util.Scanner; //导入键盘录入对象的包 2 3 public class test1 { 4 public static void main(String[] args) { 5 for (int i = 0; i < 3; i++) { 6 //创建键盘录入对象 7 Scanner sc = new Scanner(System.in); 8 //将键盘录入的用户名存储在userName中 9 String userName = sc.nextLine(); 10 //将键盘录入的密码存储在password中 11 String password = sc.nextLine(); 12 //如果是字符串常量和字符串变量比较,通常都是字符串常量调用方法,将变量当作参数传递,防止空指针异常 13 if ("admin".equals(userName) && "admin".equals(password)) { 14 System.out.println("欢迎" + userName + "登录"); 15 //跳出循环 16 break; 17 } else { 18 if (i == 2) { 19 System.out.println("您的错误次数已到,请明天再来吧"); 20 } else { 21 System.out.println("录入错误,您还有" + (2 - i) + "次机会"); 22 } 23 } 24 25 } 26 27 } 28 29 }
1 public class test3 { 2 3 public static void main(String[] args) { 4 String s = "woaining"; 5 for (int i = 0; i < s.length(); i++) { 6 System.out.print(s.charAt(i)); 7 } 8 /*或者 9 * System.out.println("-------------"); 10 for (int j = 0; j < s.length(); j++) { 11 char c = s.charAt(j); 12 System.out.print(c); 13 }*/ 14 } 15 16 }
1 package com.practice1.text1; 2 3 public class tset4 { 4 5 public static void main(String[] args) { 6 String s = "AG2@*Lg8a#!^$5H5a54fOGgH"; 7 int A = 0; 8 int a = 0; 9 int numb = 0; 10 int other = 0; 11 //获取每一个字符,通过for循环遍历 12 for (int i = 0; i < s.length(); i++) { 13 //通过索引获取每一个字符 14 char c = s.charAt(i); 15 //判断字符是否在这个范围内 16 if (c > ‘A‘ && c < ‘Z‘) { 17 //如果满足是大写字母,就让其对应的变量自增 18 A++; 19 } else if (c > ‘a‘ && c < ‘z‘) { 20 a++; 21 } else if (c > ‘0‘ && c < ‘9‘) { 22 numb++; 23 } else { 24 other++; 25 } 26 } 27 //打印每一个计数器的结果 28 System.out.println(s + "中" + "大写字母个数为:" + A + "小写字母个数为:" 29 + a + "数字个数为:" + numb + "其他类型字符个数为:" + other); 30 } 31 32 }
原文:https://www.cnblogs.com/Sherwin-liao/p/10976441.html