//创建一个集合 static List<String> phones=new ArrayList(); public static void main(String[] args) { Scanner input = new Scanner(System.in); //因为Scnner的next默认的匹配方式是遇到空格和换行符 //因此只需要改变它的匹配方式,就可以解决该问题,加入一行代码:sca.useDelimiter("\n"); input.useDelimiter("\n"); String isVil=null; do{ System.out.println("请输入手机号"); String insetList = input.next(); //替换空格 String text= insetList.replaceAll(" ",""); System.out.println(text); //判断电话格式是否正确 boolean b = Test.VilPhone(text); //判断是否是数字 if (Test.VilIsNum(text)) { if (b) { String s = Test.addList(text); System.out.println(s); } else { System.out.println("此手机号为中国大陆非法手机号"); } }else { System.out.println("本手机无法注册,非法输入"); } System.out.println("请问还有继续注册?(Y/N)"); isVil= input.next(); }while (isVil.toLowerCase().equals("y")); } public static boolean VilIsNum(String phone){ //正则 判断是否全是数字 Pattern pattern = Pattern.compile("^-?[0-9]+"); if( pattern.matcher(String.valueOf(phone)).matches()){ return true; }else{ return false; } } //判断电话格式是否正确 public static boolean VilPhone(String phone) { String regex = "^1[3456789]\\d{9}$"; boolean matches = phone.matches(regex); return matches; } public static String addList(String phone) { phones.add("18258231731"); for (String c:phones) { if (c.equals(phone)){ return "此手机已被其他用户注册"; } } phones.add(phone); return "此手机注册成功"; }