实验报告4解析

    技术2022-07-11  68

    1、编写程序,请用户输入一个 “QQ号码”,定义正则表达式,验证这个 QQ 号码是否符合以下要求:

    (1) 5 – 12 位长度; (2) 全部是数字; (3) 首位不能是 0

    import java.util.Scanner; public class work1 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String qq=sc.nextLine(); String rex="[1-9][0-9]{5,12}";//第一位是1~9的数字,第二位是0~9的数字,有5到12位 boolean f=qq.matches(rex);//判断是否匹配 if(f) { System.out.println("qq合法"); }else { System.out.println("qq非法"); } } }

    2、编写程序,请用户输入一个 “手机号码”,定义正则表达式,验证这个手机号码是否符合以下要求:

    (1)必须以数字 1 开头; (2)第二位是:3,5,7,8 中的一位; (3)剩下的全部是数字

    import java.util.Scanner; public class work2{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); String number=sc.nextLine(); String rex="[1][3,5,7,8]{1}[0-9]{9}"; boolean f=number.matches(rex); if(f) { System.out.println("number合法"); }else { System.out.println("number非法"); } } }

    3.用户从键盘输入一行文本,程序输出其中的单词。

    import java.util.Scanner; public class work1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); String regex = "[\\s\\d\\p{Punct}]+"; // 空格 数字 符号组成的正则表达式 String words[] = line.split(regex); for (int i = 0; i < words.length; i++) { int m = i + 1; System.out.println("单词" + m + ":" + words[i]); } } }

    4.

    public int indexOf(String s)从0开始检索,并返回首次出现s的位置,如果没有则返回-1. public int lastindexOf(String s)从0开始检索,并返回最后出现s的位置,如果没有则返回-1. public String substring(int startpoint)返回从开始位置(包括开始位置)到最后的字符串。

    public class work1 { public static void main(String[] args) { // TODO Auto-generated method stub String path="c:\\book\\javabook\\xml.doc"; int index=path.indexOf("\\"); index=path.indexOf("\\",index); String sub=path.substring(index); System.out.println(sub); index=path.lastIndexOf("\\"); sub=path.substring(index+1); System.out.println(sub); } }

    5.String类的 public char charAt(int index)方法可以得到当前字符串Index位置上的一个字符。编写程序,使用该方法得到一个字符串中的第一个和最后一个字符。

    public class work1 { public static void main(String[] args) { / String path="c:\\book\\javabook\\xml.doc"; System.out.println(path.charAt(0)); System.out.println(path.charAt(path.length()-1)); } }
    Processed: 0.016, SQL: 9