14.01 如何校验一个QQ号码案例
1 import java.util.Scanner;
2
3 /*
4 * 校验qq号码.
5 * 1:要求必须是5-15位数字
6 * 2:0不能开头
7 *
8 * 分析:
9 * A:键盘录入一个QQ号码
10 * B:写一个功能实现校验
11 * C:调用功能,输出结果。
12 */
13 public class Practice
14 {
15 /**
16 * @param args
17 */
18 public static void main(String[] args)
19 {
20 // 创建键盘录入对象
21 Scanner sc = new Scanner(System.in);
22 System.out.println("请输入你的QQ号码:");
23 String qq = sc.nextLine();
24
25 System.out.println("checkQQ:"+checkQQ(qq));
26 }
27 /*
28 * 写一个功能实现校验
29 返回值类型:boolean 参数列表:String qq
30 */
31 public static boolean checkQQ(String qq)
32 {
33 boolean flag = true;
34 // 校验长度
35 if (qq.length() >= 5 && qq.length() <= 15)
36 {
37 // 0不能开头
38 if (!qq.startsWith("0"))
39 {
40 // 必须是数字
41 char[] chs = qq.toCharArray();
42 for (int x = 0; x < chs.length; x++)
43 {
44 char ch = chs[x];
45 if (!Character.isDigit(ch))
46 {
47 flag = false;
48 break;
49 }
50 }
51 }
52 else
53 {
54 flag = false;
55 }
56 }
57 else
58 {
59 flag = false;
60 }
61 return flag;
62 }
63 }
14.02 正则表达式的概述和基本使用
正则表达式:是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。其实就是一种规则。有自己特殊的应用。
例:
public static boolean checkQQ(String qq)
{
//return qq.matches("[1-9][0-9]{4,14}");
return qq.matches("[1-9]\\d{4,14}");
}
14.03 正则表达式的组成规则
规则字符在java.util.regex Pattern类中
常见组成规则:
1. 字符
X 字符 x举例:‘a‘表示字符a
\\ 反斜线字符。
\n 新行(换行)符 (‘\u000A‘)
\r 回车符 (‘\u000D‘)
2. 字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,两头的字母包括在内(范围)
[0-9] 0到9的字符都包括
3. 预定义字符类
. 任何字符,如果是.字符本身,用 \.表示
\d 数字:[0-9]
\w 单词字符:[a-zA-Z_0-9],在正则表达式里面单词必须有这些东西组成
4. 边界匹配器
^ 行的开头
$ 行的结尾
\b 单词边界,就是不是单词字符的地方
5. Greedy 数量词
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次
14.04 正则表达式的判断功能
public boolean matches(String regex):
告知此字符串是否匹配给定的正则表达式。
例:校验手机号的规则
String regex = "1[358]\\d{9}";
该正则表达式表示第1位必须是1,第2位可是是358中的任意一位,后9位可以是0~9的任意数字
14.05 校验邮箱案例
例:String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
规则解释:[a-zA-Z_0-9]@[a-zA-Z_0-9]2~6次(.[a-zA-Z_0-9]2~3次)多次
14.06 正则表达式的分割功能
public String[] split(String regex):
根据给定正则表达式的匹配拆分此字符串。
14.07 分割功能的小练习
1 public class Practice
2 {
3 public static void main(String[] args)
4 {
5 String s1 = "aa,bb,cc";
6 String[] str1 = s1.split(",");
7 print(str1);
8
9 String s2 = "aa.bb.cc";
10 String[] str2 = s2.split("\\.");
11 print(str2);
12
13 String s3 = "aa bb cc";
14 String[] str3 = s3.split(" +");
15 print(str3);
16
17 String s4 = "D:\\Develop\\Java\\jdk1.7.0_51";
18 String[] str4 = s4.split("\\\\");
19 print(str4);
20 }
21 public static void print(String[] str)
22 {
23 for (int i = 0; i < str.length; i++)
24 {
25 System.out.print(str[i]+" ");
26 }
27 System.out.println();
28 }
29 }
运行结果:
aa bb cc aa bb cc aa bb cc D: Develop Java jdk1.7.0_51
14.08 把字符串中的数字排序案例
有如下一个字符串:"91 27 46 38 50"请写代码实现最终输出结果是:"27 38 46 50 91"
分析:
A:定义一个字符串
B:把字符串进行分割,得到一个字符串数组
C:把字符串数组变换成int数组
D:对int数组排序
E:把排序后的int数组再组装成一个字符串
F:输出字符串
1 public class Practice
2 {
3 public static void main(String[] args)
4 {
5 String str = "91 27 46 38 50";
6 String[] strArray = str.split(" ");
7 int[] arr = new int[strArray.length];
8 for (int i = 0; i < strArray.length; i++)
9 {
10 arr[i] = Integer.parseInt(strArray[i]);
11 }
12
13 for (int i = 0; i < arr.length-1; i++)
14 {
15 for (int j = i+1; j < arr.length; j++)
16 {
17 if(arr[i] > arr[j])
18 {
19 int temp = arr[i];
20 arr[i] = arr[j];
21 arr[j] = temp;
22 }
23 }
24 }
25 StringBuilder sb = new StringBuilder();
26 sb.append("\"");
27 for (int i = 0; i < arr.length; i++)
28 {
29 if(i == arr.length-1)
30 {
31 sb.append(arr[i]+"\"");
32 }
33 else
34 sb.append(arr[i]+" ");
35 }
36 System.out.println(sb.toString());
37 }
38 }
14.09 正则表达式的替换功能
public String replaceAll(String regex,String replacement):
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
例:
String s = "sdfds123543ghdf655334gf"; //String regex = "\\d"; //出现一次数字用*代替 String regex = "\\d+"; //出现一次或多次数字用一个*代替 String ss = s.replaceAll(regex, "*"); System.out.println(ss);
运行结果:
sdfds*ghdf*gf
14.10 Pattern和Matcher的概述
类 Pattern正则表达式的编译表示形式。
指定为字符串的正则表达式必须首先被编译为此类的实例。然后,可将得到的模式用于创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配。执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。
类 Matcher通过解释 Pattern 对 character sequence 执行匹配操作的引擎。
典型的调用顺序是
Pattern p = Pattern.compile("a*b");//将正则表达式编译成模式对象
Matcher m = p.matcher("aaaaab");//通过模式对象得到匹配器对象,需要被匹配的字符串
boolean b = m.matches();//调用匹配器对象的功能
14.11 正则表达式的获取功能
获取字符串中由三个字符组成的单词
1 import java.util.regex.Matcher;
2 import java.util.regex.Pattern;
3 public class Practice
4 {
5 public static void main(String[] args)
6 {
7 String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
8 String regex = "\\b\\w{3}\\b";
9 Pattern p = Pattern.compile(regex);
10 Matcher m = p.matcher(s);
11 while(m.find())
12 {
13 System.out.print(m.group()+" ");
14 }
15 }
16 }
运行结果:
jia jin yao xia wan gao
14.12 Math类概述和方法使用
Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
成员方法:
1. public static int abs(int a):
返回 int 值的绝对值。
2. public static double ceil(double a):
返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数。向上取整
3. public static double floor(double a):
返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。向下取整
4. public static int max(int a,int b):
返回两个 int 值中较大的一个。
5. public static double pow(double a,double b):
返回第一个参数的第二个参数次幂的值。
6. public static double random():
返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
7. public static int round(float a):
返回最接近参数的 int。
8. public static double sqrt(double a):
返回正确舍入的 double 值的正平方根。
例:
1 System.out.println("E:"+Math.E);//E:2.718281828459045
2 System.out.println("PI:"+Math.PI);//PI:3.141592653589793
3 System.out.println("abs:"+Math.abs(-10));//abs:10
4 System.out.println("ceil:"+Math.ceil(12.34));//ceil:13.0
5 System.out.println("ceil:"+Math.ceil(12.56));//ceil:13.0
6 System.out.println("floor:"+Math.floor(12.34));//floor:12.0
7 System.out.println("floor:"+Math.floor(12.56));//floor:12.0
8 System.out.println("pow:"+Math.pow(2, 3));//pow:8.0
9 System.out.println("random:"+Math.random());//random:0.8755841978783833
10 System.out.println("round:"+Math.round(12.34));//round:12
11 System.out.println("round:"+Math.round(12.56));//round:13
14.13 获取任意范围内的随机数案例
1 public static int getRandom(int start,int end)
2 {
3 int num = (int)(Math.random()*(end-start)+1)+start;
4 return num;
5 }
14.14 Random类的概述和方法使用
此类用于产生随机数
如果用相同的种子创建两个 Random 实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。
构造方法
public Random():
创建一个新的随机数生成器。此构造方法将随机数生成器的种子设置为某个值,该值与此构造方法的所有其他调用所用的值完全不同。默认的种子是当前时间的毫秒值。每次得到的数是不同的。
public Random(long seed):
使用单个 long 种子创建一个新的随机数生成器。该种子是伪随机数生成器的内部状态的初始值,该生成器可通过方法next(int) 维护。每次得到的数是相同的。
成员方法
public int nextInt():
返回下一个伪随机数,它是此随机数生成器的序列中均匀分布的 int 值。
public int nextInt(int n):
返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值。
14.15 System类中垃圾回收的方法gc()的讲解
System 类包含一些有用的类字段和方法。它不能被实例化。
成员方法
public static void gc():
运行垃圾回收器。
执行System.gc()前,系统会自动调用finalize()方法清除对象占有的资源,通过super.finalize()方式可以实现从下到上的finalize()方法的调用,即先释放自己的资源,再去释放父类的资源。
14.16 System类中的exit()和currentTimeMillis()的讲解
public static void exit(int status):
终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。
public static long currentTimeMillis():
返回以毫秒为单位的当前时间。
14.17 System类中的arraycopy()的讲解
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length):
从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
例:
1 int[] arr1 = {11,22,33,44,55};
2 int[] arr2 = {6,7,8,9,10};
3 System.arraycopy(arr1, 1, arr2, 2, 2);
4 System.out.println(Arrays.toString(arr1));
5 System.out.println(Arrays.toString(arr2));
运行结果:
[11, 22, 33, 44, 55] [6, 7, 22, 33, 10]
14.18 BigInteger的概述和构造方法
BigInteger类概述:可以让超过Integer范围内的数据进行运算
构造方法:
public BigInteger(String val):
将 BigInteger 的十进制字符串表示形式转换为 BigInteger。
例:
System.out.println(Integer.MAX_VALUE);//2147483647
BigInteger bi = new BigInteger("2147483648");
System.out.println(bi);
14.19 BigInteger的加减乘除法的使用
成员方法
1. public BigInteger add(BigInteger val):返回其值为 (this + val) 的 BigInteger。
2. public BigInteger subtract(BigInteger val):返回其值为 (this - val) 的 BigInteger。
3. public BigInteger multiply(BigInteger val):返回其值为 (this * val) 的 BigInteger。
4. public BigInteger divide(BigInteger val):返回其值为 (this / val) 的 BigInteger。
5. public BigInteger[] divideAndRemainder(BigInteger val):返回包含 (this / val) 后跟 (this % val) 的两个 BigInteger 的数组。
例:
1 BigInteger bi1 = new BigInteger("100");
2 BigInteger bi2 = new BigInteger("50");
3
4 System.out.println("加法:"+bi1.add(bi2));
5 System.out.println("减法:"+bi1.subtract(bi2));
6 System.out.println("乘法:"+bi1.multiply(bi2));
7 System.out.println("除法:"+bi1.divide(bi2));
8
9 BigInteger[] bis = bi1.divideAndRemainder(bi2);
10 System.out.println("商:"+bis[0]);
11 System.out.println("余数:"+bis[1]);
运行结果:
加法:150 减法:50 乘法:5000 除法:2 商:2 余数:0
14.20 BigDecimal的引入和概述
由于在运算的时候,float类型和double很容易丢失精度。
例:
System.out.println(0.09 + 0.01);//0.09999999999999999 System.out.println(1.0 - 0.32);//0.6799999999999999 System.out.println(1.015 * 100);//101.49999999999999 System.out.println(1.301 / 100);//0.013009999999999999
所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal
BigDecimal类概述:不可变的、任意精度的有符号十进制数。
构造方法
public BigDecimal(String val):
将 BigDecimal 的字符串表示形式转换为 BigDecimal。
14.21 BigDecimal的加减乘除法的使用
成员方法:
1. public BigDecimal add(BigDecimal augend)
返回一个 BigDecimal,其值为 (this + augend),其标度为 max(this.scale(), augend.scale())。
2. public BigDecimal subtract(BigDecimal subtrahend)
返回一个 BigDecimal,其值为 (this - subtrahend),其标度为 max(this.scale(), subtrahend.scale())。
3. public BigDecimal multiply(BigDecimal multiplicand)
返回一个 BigDecimal,其值为 (this × multiplicand),其标度为 (this.scale() + multiplicand.scale())。
4. public BigDecimal divide(BigDecimal divisor)
返回一个 BigDecimal,其值为 (this / divisor),其首选标度为 (this.scale() - divisor.scale());如果无法表示准确的商值(因为它有无穷的十进制扩展),则抛出 ArithmeticException。
5. public BigDecimal divide(BigDecimal divisor,int scale,RoundingMode roundingMode)
返回一个 BigDecimal,其值为 (this / divisor),其标度为指定标度。如果必须执行舍入,以生成具有指定标度的结果,则应用指定的舍入模式。
例:
1 BigDecimal bd1 = new BigDecimal("0.09");
2 BigDecimal bd2 = new BigDecimal("0.01");
3 System.out.println("加法:"+bd1.add(bd2));
4
5 BigDecimal bd3 = new BigDecimal("1.0");
6 BigDecimal bd4 = new BigDecimal("0.32");
7 System.out.println("减法:"+bd3.subtract(bd4));
8
9 BigDecimal bd5 = new BigDecimal("1.015");
10 BigDecimal bd6 = new BigDecimal("100");
11 System.out.println("乘法:"+bd5.multiply(bd6));
12
13 BigDecimal bd7 = new BigDecimal("1.301");
14 BigDecimal bd8 = new BigDecimal("100");
15 System.out.println("除法:"+bd7.divide(bd8));
16
17
18 System.out.println("除法:"+bd7.divide(bd8,3,BigDecimal.ROUND_HALF_UP));
运行结果:
加法:0.10 减法:0.68 乘法:101.500 除法:0.01301 除法:0.013
14.22 Date的概述和构造方法
Date类概述:类 Date 表示特定的瞬间,精确到毫秒。
构造方法
public Date():
分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
public Date(long date):
分配 Date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数。
例:
1 Date d1 = new Date(); 2 System.out.println(d1);//Thu May 21 16:56:34 CST 2014 3 Date d2 = new Date(3600000); 4 System.out.println(d2);//Thu Jan 01 09:00:00 CST 1970
14.23 Date类中日期和毫秒的相互转换
成员方法
public long getTime():
返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
public void setTime(long time):
设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
例:
Date d = new Date(); //获取时间毫秒值 System.out.println(d.getTime());1432198839578 //设置时间 d.setTime(1000); System.out.println(d);Thu Jan 01 08:00:01 CST 1970
Date得到毫秒值: 使用Date对象的getTime()方法
毫秒值得到Date: 1.构造方法2.使用Date对象的setTime()方法
14.24 DateFormat实现日期和字符串的相互转换
DateFormat类概述:DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。
日期/时间格式化子类(如 SimpleDateFormat)允许进行格式化(也就是日期 -> 文本)、解析(文本-> 日期)和标准化
是抽象类,所以要使用其具体子类SimpleDateFormat
SimpleDateFormat构造方法:
public SimpleDateFormat():
用默认的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
public SimpleDateFormat(String pattern):
用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
成员方法
public final String format(Date date):
将一个 Date 格式化为日期/时间字符串。
public Date parse(String source)throws ParseException:
从给定字符串的开始解析文本,以生成一个日期。该方法不使用给定字符串的整个文本。
例:
1 //创建日期对象
2 Date d = new Date();
3 //创建格式化对象,默认格式
4 //SimpleDateFormat sdf = new SimpleDateFormat();
5 //自定义格式
6 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
7 String str = sdf.format(d);
8 //默认格式的输出
9 //System.out.println(str);//15-3-21 下午5:11
10 //自定义格式的输出
11 System.out.println(str);//2015年03月21日 17:16:01
12
13
14
15 String s = "2009-08-08 12:34:45";
16 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
17 //字符串转日期
18 Date d2 = sdf2.parse(s);
19 System.out.println(d2);//Sat Aug 08 12:34:45 CST 2009
14.25 日期工具类的编写和测试案例
//测试类
import java.text.ParseException;
import java.util.Date;
public class Practice
{
public static void main(String[] args) throws ParseException
{
Date d = new Date();
String s = DateUtil.dateToString(d, "yyyy-MM-dd HH:mm:ss");
System.out.println(s);
Date d2 = DateUtil.stringToDate("2008-08-08", "yyyy-MM-dd");
System.out.println(d2);
}
}
1 //工具类
2 import java.text.ParseException;
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 public class DateUtil
7 {
8 private DateUtil(){}
9
10 public static String dateToString(Date d,String format)
11 {
12 SimpleDateFormat sdf = new SimpleDateFormat(format);
13 String s = sdf.format(d);
14 return s;
15 }
16 public static Date stringToDate(String s,String format) throws ParseException
17 {
18 SimpleDateFormat sdf = new SimpleDateFormat(format);
19 Date d = sdf.parse(s);
20 return d;
21 }
22 }
14.26 计算你来到这个世界多少天案例
1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4
5 public class Practice
6 {
7 public static void main(String[] args) throws ParseException
8 {
9 String date = "1990-05-10";
10 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
11 //将字符串转为日期对象
12 Date d = sdf.parse(date);
13 //通过日期对象得到毫秒值
14 long time1 = d.getTime();
15 //获得当前时间的毫秒值
16 long time2 = System.currentTimeMillis();
17 long time = time2 - time1;
18 System.out.println(time/1000/60/60/24+"天");
19 }
20 }
14.27 Calendar类的概述和获取日历字段的方法
Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
成员方法:
1. public static Calendar getInstance():
使用默认时区和语言环境获得一个日历。返回的 Calendar 基于当前时间,使用了默认时区和默认语言环境。
2. public int get(int field):
返回给定日历字段的值。
例:
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR));//2015
14.28 Calendar类的add()和set()方法
1. public abstract void add(int field,int amount):
根据日历的规则,为给定的日历字段添加或减去指定的时间量。
2. public final void set(int year,int month,int date):
设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。保留其他日历字段以前的值。
例:
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -3);
System.out.println(c.get(Calendar.YEAR));//2012
14.29 获取任意年份的2月份有多少天案例
1 import java.util.Calendar;
2 import java.util.Scanner;
3
4 public class Practice
5 {
6 public static void main(String[] args)
7 {
8 Scanner sc = new Scanner(System.in);
9 System.out.println("请输入年份:");
10 int year = sc.nextInt();
11
12 Calendar c = Calendar.getInstance();
13 //将时间定在任意一年的3月1日
14 c.set(year, 2, 1);
15 c.add(Calendar.DAY_OF_MONTH, -1);
16 int day = c.get(Calendar.DAY_OF_MONTH);
17 System.out.println(year+"年的二月有"+day+"天");
18
19 }
20 }
运行结果:
请输入年份:
2008
2008年的二月有29天
原文:http://www.cnblogs.com/hoop-superman/p/5495707.html