1. 校验QQ号码的案例,如下:
1 package cn.itcast_01; 2 3 import java.util.Scanner; 4 5 /* 6 * 校验qq号码. 7 * 1:要求必须是5-15位数字 8 * 2:0不能开头 9 * 10 * 分析: 11 * A:键盘录入一个QQ号码 12 * B:写一个功能实现校验 13 * C:调用功能,输出结果。 14 */ 15 public class RegexDemo { 16 public static void main(String[] args) { 17 // 创建键盘录入对象 18 Scanner sc = new Scanner(System.in); 19 System.out.println("请输入你的QQ号码:"); 20 String qq = sc.nextLine(); 21 22 System.out.println("checkQQ:"+checkQQ(qq)); 23 } 24 25 /* 26 * 写一个功能实现校验 两个明确: 明确返回值类型:boolean 明确参数列表:String qq 27 */ 28 public static boolean checkQQ(String qq) { 29 boolean flag = true; 30 31 // 校验长度 32 if (qq.length() >= 5 && qq.length() <= 15) { 33 // 0不能开头 34 if (!qq.startsWith("0")) { 35 // 必须是数字 36 char[] chs = qq.toCharArray(); 37 for (int x = 0; x < chs.length; x++) { 38 char ch = chs[x]; 39 if (!Character.isDigit(ch)) { 40 flag = false; 41 break; 42 } 43 } 44 } else { 45 flag = false; 46 } 47 } else { 48 flag = false; 49 } 50 51 return flag; 52 } 53 }
运行效果如下: