您的位置:首页 > 编程语言 > Java开发

JavaSE学习总结第14天_API常用对象4

2015-05-23 22:41 344 查看
14.01 如何校验一个QQ号码案例

import java.util.Scanner;

/*
* 校验qq号码.
*         1:要求必须是5-15位数字
*         2:0不能开头
*
* 分析:
*         A:键盘录入一个QQ号码
*         B:写一个功能实现校验
*         C:调用功能,输出结果。
*/
public class Practice
{
/**
* @param args
*/
public static void main(String[] args)
{
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的QQ号码:");
String qq = sc.nextLine();

System.out.println("checkQQ:"+checkQQ(qq));
}
/*
* 写一个功能实现校验
返回值类型:boolean 参数列表:String qq
*/
public static boolean checkQQ(String qq)
{
boolean flag = true;
// 校验长度
if (qq.length() >= 5 && qq.length() <= 15)
{
// 0不能开头
if (!qq.startsWith("0"))
{
// 必须是数字
char[] chs = qq.toCharArray();
for (int x = 0; x < chs.length; x++)
{
char ch = chs[x];
if (!Character.isDigit(ch))
{
flag = false;
break;
}
}
}
else
{
flag = false;
}
}
else
{
flag = false;
}
return flag;
}
}


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 分割功能的小练习

public class Practice
{
public static void main(String[] args)
{
String s1 = "aa,bb,cc";
String[] str1 = s1.split(",");
print(str1);

String s2 = "aa.bb.cc";
String[] str2 = s2.split("\\.");
print(str2);

String s3 = "aa  bb       cc";
String[] str3 = s3.split(" +");
print(str3);

String s4 = "D:\\Develop\\Java\\jdk1.7.0_51";
String[] str4 = s4.split("\\\\");
print(str4);
}
public static void print(String[] str)
{
for (int i = 0; i < str.length; i++)
{
System.out.print(str[i]+" ");
}
System.out.println();
}
}


运行结果:

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:输出字符串

public class Practice
{
public static void main(String[] args)
{
String str = "91 27 46 38 50";
String[] strArray = str.split(" ");
int[] arr = new int[strArray.length];
for (int i = 0; i < strArray.length; i++)
{
arr[i] = Integer.parseInt(strArray[i]);
}

for (int i = 0; i < arr.length-1; i++)
{
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append("\"");
for (int i = 0; i < arr.length; i++)
{
if(i == arr.length-1)
{
sb.append(arr[i]+"\"");
}
else
sb.append(arr[i]+" ");
}
System.out.println(sb.toString());
}
}


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通过解释 Patterncharacter sequence 执行匹配操作的引擎。

典型的调用顺序是

Pattern p = Pattern.compile("a*b");//将正则表达式编译成模式对象

Matcher m = p.matcher("aaaaab");//通过模式对象得到匹配器对象,需要被匹配的字符串

boolean b = m.matches();//调用匹配器对象的功能

14.11 正则表达式的获取功能

获取字符串中由三个字符组成的单词

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Practice
{
public static void main(String[] args)
{
String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
String regex = "\\b\\w{3}\\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find())
{
System.out.print(m.group()+" ");
}
}
}


运行结果:

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 值的正平方根。

例:

System.out.println("E:"+Math.E);//E:2.718281828459045
System.out.println("PI:"+Math.PI);//PI:3.141592653589793
System.out.println("abs:"+Math.abs(-10));//abs:10
System.out.println("ceil:"+Math.ceil(12.34));//ceil:13.0
System.out.println("ceil:"+Math.ceil(12.56));//ceil:13.0
System.out.println("floor:"+Math.floor(12.34));//floor:12.0
System.out.println("floor:"+Math.floor(12.56));//floor:12.0
System.out.println("pow:"+Math.pow(2, 3));//pow:8.0
System.out.println("random:"+Math.random());//random:0.8755841978783833
System.out.println("round:"+Math.round(12.34));//round:12
System.out.println("round:"+Math.round(12.56));//round:13


14.13 获取任意范围内的随机数案例

public static int getRandom(int start,int end)
{
int num = (int)(Math.random()*(end-start)+1)+start;
return num;
}


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):

从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

例:

int[] arr1 = {11,22,33,44,55};
int[] arr2 = {6,7,8,9,10};
System.arraycopy(arr1, 1, arr2, 2, 2);
System.out.println(Arrays.toString(arr1));
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 的数组。

例:

BigInteger bi1 = new BigInteger("100");
BigInteger bi2 = new BigInteger("50");

System.out.println("加法:"+bi1.add(bi2));
System.out.println("减法:"+bi1.subtract(bi2));
System.out.println("乘法:"+bi1.multiply(bi2));
System.out.println("除法:"+bi1.divide(bi2));

BigInteger[] bis = bi1.divideAndRemainder(bi2);
System.out.println("商:"+bis[0]);
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),其标度为指定标度。如果必须执行舍入,以生成具有指定标度的结果,则应用指定的舍入模式。

例:

BigDecimal bd1 = new BigDecimal("0.09");
BigDecimal bd2 = new BigDecimal("0.01");
System.out.println("加法:"+bd1.add(bd2));

BigDecimal bd3 = new BigDecimal("1.0");
BigDecimal bd4 = new BigDecimal("0.32");
System.out.println("减法:"+bd3.subtract(bd4));

BigDecimal bd5 = new BigDecimal("1.015");
BigDecimal bd6 = new BigDecimal("100");
System.out.println("乘法:"+bd5.multiply(bd6));

BigDecimal bd7 = new BigDecimal("1.301");
BigDecimal bd8 = new BigDecimal("100");
System.out.println("除法:"+bd7.divide(bd8));

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)以来的指定毫秒数。

例:

Date d1 = new Date();
System.out.println(d1);//Thu May 21 16:56:34 CST 2014
Date d2 = new Date(3600000);
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:

从给定字符串的开始解析文本,以生成一个日期。该方法不使用给定字符串的整个文本。

例:

//创建日期对象
Date d = new Date();
//创建格式化对象,默认格式
//SimpleDateFormat sdf = new SimpleDateFormat();
//自定义格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str = sdf.format(d);
//默认格式的输出
//System.out.println(str);//15-3-21 下午5:11
//自定义格式的输出
System.out.println(str);//2015年03月21日 17:16:01

String s = "2009-08-08 12:34:45";
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//字符串转日期
Date d2 = sdf2.parse(s);
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);

}
}


//工具类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil
{
private DateUtil(){}

public static String dateToString(Date d,String format)
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
String s = sdf.format(d);
return s;
}
public static Date stringToDate(String s,String format) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d = sdf.parse(s);
return d;
}
}


14.26 计算你来到这个世界多少天案例

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Practice
{
public static void main(String[] args) throws ParseException
{
String date = "1990-05-10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//将字符串转为日期对象
Date d = sdf.parse(date);
//通过日期对象得到毫秒值
long time1 = d.getTime();
//获得当前时间的毫秒值
long time2 = System.currentTimeMillis();
long time = time2 - time1;
System.out.println(time/1000/60/60/24+"天");
}
}


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月份有多少天案例

import java.util.Calendar;
import java.util.Scanner;

public class Practice
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份:");
int year = sc.nextInt();

Calendar c = Calendar.getInstance();
//将时间定在任意一年的3月1日
c.set(year, 2, 1);
c.add(Calendar.DAY_OF_MONTH, -1);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"年的二月有"+day+"天");

}
}


运行结果:

请输入年份:

2008

2008年的二月有29天
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: