14. 正则表达式和常见类 (Math、Random、System、BigInteger、BigDecimal、Date_DateFormat、Calendar)

本文主要是介绍14. 正则表达式和常见类 (Math、Random、System、BigInteger、BigDecimal、Date_DateFormat、Calendar),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

1:正则表达式(理解)

2:Math数学运算的类(掌握)

3:Random随机数类(理解)

4:System(掌握)

5:BigInteger大整型数类(理解)

6:BigDecimal大浮点数类(理解)

7:Date/DateFormat日期类(掌握)

8:Calendar日历类(掌握)


1:正则表达式(理解)

       (1)就是符合一定规则的字符串

       (2)常见规则

              A:字符

                     x 字符 x。举例:'a'表示字符a

                     \\ 反斜线字符。

                     \n 新行(换行)符 ('\u000A')

                     \r 回车符 ('\u000D')

              B:字符类

                     [abc] a、b 或c(简单类)

                     [^abc] 任何字符,除了 a、b或 c(否定)

                     [a-zA-Z] a到 z 或A到 Z,两头的字母包括在内(范围)

                     [0-9] 0到9的字符都包括

              C:预定义字符类(反义预定义字符类,字母全部大写)

                     . 任何字符。我的就是.字符本身,怎么表示呢? \.

                     \d 数字:[0-9]

                     \w 单词字符:[a-zA-Z_0-9]

                            在正则表达式里面组成单词的东西必须有这些东西组成

              D:边界匹配器

                     ^ 行的开头

                     $ 行的结尾

                     \b 单词边界

                            就是不是单词字符的地方。

                            举例:hello world?haha;xixi

              E:Greedy 数量词

                     X? X,一次或一次也没有

                     X* X,零次或多次

                     X+ X,一次或多次

                     X{n} X,恰好 n 次

                     X{n,} X,至少 n 次

                     X{n,m} X,至少 n 次,但是不超过 m 次

       (3)常见功能:(分别用的是谁呢?)

              A:判断功能

                     String类的public boolean matches(String regex)

              B:分割功能

                     String类的public String[] split(String regex)

              C:替换功能

                     String类的public String replaceAll(String regex,Stringreplacement)

              D:获取功能

                     Pattern和Matcher

                            Pattern p =Pattern.compile("a*b");

                            Matcher m =p.matcher("aaaaab");

                            find():查找存不存在

                            group():获取刚才查找过的数据

       (4)案例

              A:判断电话号码和邮箱

 * 分析:

 *             A:键盘录入手机号码

 *             B:定义手机号码的规则

 *                    13436975980

 *                    13688886868

 *                    13866668888

 *                    13456789012

 *                    13123456789

 *                    18912345678

 *                    18886867878

 *                    18638833883

 *             C:调用功能,判断即可

 *             D:输出结果

 

public class RegexDemo {publicstatic void main(String[] args) {//键盘录入手机号码Scannersc = new Scanner(System.in);System.out.println("请输入你的手机号码:");Stringphone = sc.nextLine();//定义手机号码的规则Stringregex = "1[38]\\d{9}";//调用功能,判断即可booleanflag = phone.matches(regex);//输出结果System.out.println("flag:"+flag);}
}

* 校验邮箱

 * 分析:

 *          A:键盘录入邮箱

 *          B:定义邮箱的规则

 *                 1517806580@qq.com

 *                 liuyi@163.com

 *                 linqingxia@126.com

 *                 fengqingyang@sina.com.cn

 *                 fqy@itcast.cn

 *          C:调用功能,判断即可

 *          D:输出结果

 

public class RegexTest {publicstatic void main(String[] args) {//键盘录入邮箱Scannersc = new Scanner(System.in);System.out.println("请输入邮箱:");Stringemail = sc.nextLine();//定义邮箱的规则//Stringregex = "[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\.[a-zA-Z_0-9]{2,3})+";Stringregex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";//调用功能,判断即可boolean flag =email.matches(regex);//输出结果System.out.println("flag:"+flag);}
}

              B:按照不同的规则分割数据

 * 举例:

 *          百合网,世纪佳缘,珍爱网,QQ

 *          搜索好友

 *                 性别:女

 *                 范围:"18-24"

 *          age>=18&& age<=24

 

public class RegexDemo {publicstatic void main(String[] args) {//定义一个年龄搜索范围Stringages = "18-24";//定义规则Stringregex = "-";//调用方法String[]strArray = ages.split(regex);
//            //遍历
//            for(intx=0; x<strArray.length; x++){
//                   System.out.println(strArray[x]);
//            }//如何得到int类型的呢?intstartAge = Integer.parseInt(strArray[0]);intendAge = Integer.parseInt(strArray[1]);//键盘录入年龄Scannersc = new Scanner(System.in);System.out.println("请输入你的年龄:");intage = sc.nextInt();if(age>=startAge&& age<=endAge) {System.out.println("你就是我想找的");}else{System.out.println("不符合我的要求,gun");}}
}

* 分割功能练习

 

public class RegexDemo2 {publicstatic void main(String[] args) {//定义一个字符串Strings1 = "aa,bb,cc";//直接分割String[]str1Array = s1.split(",");for(int x = 0; x < str1Array.length; x++) {System.out.println(str1Array[x]);}System.out.println("---------------------");Strings2 = "aa.bb.cc";String[]str2Array = s2.split("\\.");for(int x = 0; x < str2Array.length; x++) {System.out.println(str2Array[x]);}System.out.println("---------------------");Strings3 = "aa    bb                cc";String[]str3Array = s3.split(" +");for(int x = 0; x < str3Array.length; x++) {System.out.println(str3Array[x]);}System.out.println("---------------------");//硬盘上的路径,我们应该用\\替代\Strings4 = "E:\\JavaSE\\day14\\avi";String[]str4Array = s4.split("\\\\");for(int x = 0; x < str4Array.length; x++) {System.out.println(str4Array[x]);}System.out.println("---------------------");}
}

 * 我有如下一个字符串:"91 27 46 38 50"

 * 请写代码实现最终输出结果是:"27 38 46 50 91"

 * 分析:

 *          A:定义一个字符串

 *          B:把字符串进行分割,得到一个字符串数组

 *          C:把字符串数组变换成int数组

 *          D:对int数组排序

 *          E:把排序后的int数组在组装成一个字符串

 *          F:输出字符串

 

public class RegexTest {publicstatic void main(String[] args) {//定义一个字符串Strings = "91 27 46 38 50";//把字符串进行分割,得到一个字符串数组String[]strArray = s.split(" ");//把字符串数组变换成int数组int[]arr = new int[strArray.length];for(int x = 0; x < arr.length; x++) {arr[x] =Integer.parseInt(strArray[x]);}// 对int数组排序Arrays.sort(arr);// 把排序后的int数组在组装成一个字符串StringBuilder sb = newStringBuilder();for (int x = 0; x < arr.length; x++) {sb.append(arr[x]).append("");}//转化为字符串Stringresult = sb.toString().trim();//输出字符串System.out.println("result:"+result);}
}

              C:把论坛中的数字替换为*

 

public class RegexDemo {publicstatic void main(String[] args) {//定义一个字符串Strings = "helloqq12345worldkh622112345678java";//我要去除所有的数字,用*给替换掉//String regex = "\\d+";//String regex = "\\d";//String ss = "*";// 直接把数字干掉String regex = "\\d+";String ss = "";String result =s.replaceAll(regex, ss);System.out.println(result);}
}

              D:获取字符串中由3个字符组成的单词

 * 获取下面这个字符串中由三个字符组成的单词

 * da jia ting wo shuo,jin tian yao xia yu,bushang wan zi xi,gao xing bu?

 

public class RegexDemo2 {publicstatic void main(String[] args) {//定义字符串Strings = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xingbu?";//规则Stringregex = "\\b\\w{3}\\b";//把规则编译成模式对象Patternp = Pattern.compile(regex);//通过模式对象得到匹配器对象Matcherm = p.matcher(s);//调用匹配器对象的功能//通过find方法就是查找有没有满足条件的子串//public boolean find()//boolean flag = m.find();//System.out.println(flag);// // 如何得到值呢?// // public String group()//String ss = m.group();//System.out.println(ss);再来一次//flag = m.find();//System.out.println(flag);//ss = m.group();//System.out.println(ss);while(m.find()) {System.out.println(m.group());}//注意:一定要先find(),然后才能group()//IllegalStateException: No match found//String ss = m.group();//System.out.println(ss);}
}

2:Math数学运算的类(掌握)

       (1)针对数学运算进行操作的类

       (2)常见方法

              public static int abs(int a):                               绝对值

              public static double ceil(double a):                      向上取整

             publicstatic double floor(double a):                    向下取整

             publicstatic int max(int a,int b):                         最大值 (min自学)

              public static double pow(double a,double b):       a的b次幂

             publicstatic double random():                            随机数[0.0,1.0)

              public static int round(float a)                            四舍五入(参数为double的自学)

             publicstatic double sqrt(double a):                     正平方根

------------------------------------------------------------------------------------------------------------------------------------------

 

public class MathDemo {publicstatic void main(String[] args) {//public static final double PISystem.out.println("PI:"+ Math.PI);//public static final double ESystem.out.println("E:"+ Math.E);System.out.println("--------------");//public static int abs(int a):绝对值System.out.println("abs:"+ Math.abs(10));System.out.println("abs:"+ Math.abs(-10));System.out.println("--------------");//public static double ceil(double a):向上取整System.out.println("ceil:"+ Math.ceil(12.34));System.out.println("ceil:" +Math.ceil(12.56));System.out.println("--------------");//public static double floor(double a):向下取整System.out.println("floor:"+ Math.floor(12.34));System.out.println("floor:"+ Math.floor(12.56));System.out.println("--------------");//public static int max(int a,int b):最大值System.out.println("max:"+ Math.max(12, 23));//需求:我要获取三个数据中的最大值//方法的嵌套调用System.out.println("max:"+ Math.max(Math.max(12, 23), 18));//需求:我要获取四个数据中的最大值System.out.println("max:"+Math.max(Math.max(12, 78), Math.max(34, 56)));System.out.println("--------------");//public static double pow(double a,double b):a的b次幂System.out.println("pow:"+ Math.pow(2, 3));System.out.println("--------------");//public static double random():随机数[0.0,1.0)System.out.println("random:"+ Math.random());//获取一个1-100之间的随机数System.out.println("random:"+ ((int) (Math.random() * 100) + 1));System.out.println("--------------");//public static int round(float a) 四舍五入(参数为double的自学)System.out.println("round:"+ Math.round(12.34f));System.out.println("round:"+ Math.round(12.56f));System.out.println("--------------");//publicstatic double sqrt(double a):正平方根System.out.println("sqrt:"+Math.sqrt(4));}
}

       (3)案例:

              A:猜数字小游戏

              B:获取任意范围的随机数

* 分析:

 *             A:键盘录入两个数据。

 *                    intstrat;

 *                    intend;

 *             B:想办法获取在start到end之间的随机数

 *                    我写一个功能实现这个效果,得到一个随机数。(int)

 *             C:输出这个随机数

 

public class MathDemo {publicstatic void main(String[] args) {Scannersc = new Scanner(System.in);System.out.println("请输入开始数:");intstart = sc.nextInt();System.out.println("请输入结束数:");intend = sc.nextInt();for(int x = 0; x < 100; x++) {//调用功能intnum = getRandom(start, end);//输出结果System.out.println(num);}}// 写一个功能 两个明确: 返回值类型:int 参数列表:intstart,int endpublicstatic int getRandom(int start, int end) {//回想我们讲过的1-100之间的随机数//int number = (int) (Math.random() * 100) + 1;//int number = (int) (Math.random() * end) + start;//发现有问题了,怎么办呢?intnumber = (int) (Math.random() * (end - start + 1)) + start;return  number;}
} 

3:Random随机数类(理解)

       (1)用于产生随机数的类

       (2)构造方法:

              public Random():                 没有给种子,用的是默认种子,是当前时间的毫秒值

             publicRandom(long seed):    给出指定的种子

             给定种子后,每次得到的随机数是相同的。

       (3)成员方法:

              public int nextInt()               返回int范围内的随机数

              public int nextInt(int n) 返回[0,n)范围内的随机数

 

public class RandomDemo {publicstatic void main(String[] args) {//创建对象//Random r = new Random();Randomr = new Random(1111);for(int x = 0; x < 10; x++) {// int num = r.nextInt();intnum = r.nextInt(100) + 1;System.out.println(num);}}
}

4:System(掌握)

       (1)System类包含一些有用的类字段和方法。它不能被实例化。

       (2)成员方法

              A: public static void gc():                         运行垃圾回收器

              B: public static void exit(int status)              退出jvm

              C: public static long currentTimeMillis()      获取当前时间的毫秒值

D: public static void arraycopy(Object src,int srcPos,Object dest,int destPos,intlength)

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

 

public class SystemDemo {publicstatic void main(String[] args) {//System.out.println("我们喜欢林青霞(东方不败)");//System.exit(0);//System.out.println("我们也喜欢赵雅芝(白娘子)");//System.out.println(System.currentTimeMillis());// 单独得到这样的实际目前对我们来说意义不大//那么,它到底有什么作用呢?//要求:请大家给我统计这段程序的运行时间longstart = System.currentTimeMillis();for(int x = 0; x < 100000; x++) {System.out.println("hello"+ x);}long end = System.currentTimeMillis();System.out.println("共耗时:" + (end -start) + "毫秒");}
}

 

 

publicclass SystemDemo {public static void main(String[] args) {// 定义数组int[] arr = { 11, 22, 33, 44, 55 };int[] arr2 = { 6, 7, 8, 9, 10 };// 请大家看这个代码的意思System.arraycopy(arr, 1, arr2, 2, 2);System.out.println(Arrays.toString(arr));System.out.println(Arrays.toString(arr2));}
}

5:BigInteger大整型数类(理解)

       (1) 可以让超过Integer范围内的数据进行运算

       (2)构造方法 

              A:BigInteger(Strings)

 

publicclass BigIntegerDemo {public static void main(String[] args) {//这几个测试,是为了简单超过int范围内,Integer就不能再表示,所以就更谈不上计算了。// Integer i = new Integer(100);//System.out.println(i);// //System.out.println(Integer.MAX_VALUE);// Integer ii = newInteger("2147483647");// System.out.println(ii);// // NumberFormatException// Integer iii = newInteger("2147483648");// System.out.println(iii);// 通过大整数来创建对象BigInteger bi = newBigInteger("2147483648");System.out.println("bi:"+ bi);}
}

       (3)成员方法

              public BigInteger add(BigInteger val):                              加

             publicBigInteger subtract(BigInteger val):                        减

             publicBigInteger multiply(BigInteger val):                       乘

             publicBigInteger divide(BigInteger val):                          除

             publicBigInteger[] divideAndRemainder(BigInteger val):   返回商和余数的数组

 

public class BigIntegerDemo {publicstatic void main(String[] args) {BigIntegerbi1 = new BigInteger("100");BigIntegerbi2 = new BigInteger("50");//public BigInteger add(BigInteger val):加System.out.println("add:"+ bi1.add(bi2));//public BigInteger subtract(BigInteger val):加System.out.println("subtract:"+ bi1.subtract(bi2));//public BigInteger multiply(BigInteger val):加System.out.println("multiply:"+ bi1.multiply(bi2));//public BigInteger divide(BigInteger val):加System.out.println("divide:"+ bi1.divide(bi2));//public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组BigInteger[]bis = bi1.divideAndRemainder(bi2);System.out.println("商:" + bis[0]);System.out.println("余数:" + bis[1]);}
}

6:BigDecimal大浮点数类(理解)

       (1)由于在运算的时候,float类型和double很容易丢失精度,演示案例。所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal

BigDecimal类:不可变的、任意精度的有符号十进制数,可以解决数据丢失问题。所以,针对浮点数据的操作建议采用BigDecimal。(金融相关的项目)

       (2)构造方法

              A:BigDecimal(String s)

       (3)成员方法:

              A: public BigDecimal add(BigDecimal augend)                                             加

              B: public BigDecimal subtract(BigDecimal subtrahend)                                  减

              C: public BigDecimal multiply(BigDecimal multiplicand)                               乘

              D: public BigDecimal divide(BigDecimal divisor)                                          除

              E: public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)    自己保留小数几位

 

public class BigDecimalDemo {publicstatic void main(String[] args) {//System.out.println(0.09 + 0.01);// System.out.println(1.0 - 0.32);// System.out.println(1.015 * 100);// System.out.println(1.301 / 100);BigDecimal bd1 = newBigDecimal("0.09");BigDecimalbd2 = new BigDecimal("0.01");System.out.println("add:"+ bd1.add(bd2));System.out.println("-------------------");BigDecimalbd3 = new BigDecimal("1.0");BigDecimalbd4 = new BigDecimal("0.32");System.out.println("subtract:"+ bd3.subtract(bd4));System.out.println("-------------------");BigDecimalbd5 = new BigDecimal("1.015");BigDecimalbd6 = new BigDecimal("100");System.out.println("multiply:"+ bd5.multiply(bd6));System.out.println("-------------------");BigDecimalbd7 = new BigDecimal("1.301");BigDecimalbd8 = new BigDecimal("100");System.out.println("divide:"+ bd7.divide(bd8));System.out.println("divide:"+bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));System.out.println("divide:"+bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));}
}

7:Date/DateFormat日期类(掌握)

       (1)Date是日期类,可以精确到毫秒。

              A:构造方法

                     Date():                  根据当前的默认毫秒值创建日期对象

                     Date(long date):   根据给定的毫秒值创建日期对象

 

public class DateDemo {publicstatic void main(String[] args) {//创建对象Dated = new Date();System.out.println("d:"+ d);//创建对象//long time = System.currentTimeMillis();longtime = 1000 * 60 * 60; // 1小时Dated2 = new Date(time);System.out.println("d2:"+ d2);}
}

              B:成员方法

                     public long getTime():                 获取时间,以毫秒为单位

                    publicvoid setTime(long time):     设置时间

 * 从Date得到一个毫秒值

 *          getTime()

 * 把一个毫秒值转换为Date

 *          构造方法

 *          setTime(longtime)

 

public class DateDemo {publicstatic void main(String[] args) {//创建对象Dated = new Date();//获取时间longtime = d.getTime();System.out.println(time);//System.out.println(System.currentTimeMillis());System.out.println("d:"+ d);//设置时间d.setTime(1000);System.out.println("d:"+ d);}
}

              C:日期和毫秒值的相互转换

              案例:你来到这个世界多少天了?

 * 分析:

 *          A:键盘录入你的出生的年月日

 *          B:把该字符串转换为一个日期

 *          C:通过该日期得到一个毫秒值

 *          D:获取当前时间的毫秒值

 *          E:用D-C得到一个毫秒值

 *          F:把E的毫秒值转换为年

 *                 /1000/60/60/24

 

public class MyYearOldDemo {publicstatic void main(String[] args) throws ParseException {//键盘录入你的出生的年月日Scannersc = new Scanner(System.in);System.out.println("请输入你的出生年月日:");Stringline = sc.nextLine();//把该字符串转换为一个日期SimpleDateFormatsdf = new SimpleDateFormat("yyyy-MM-dd");Dated = sdf.parse(line);//通过该日期得到一个毫秒值longmyTime = d.getTime();//获取当前时间的毫秒值longnowTime = System.currentTimeMillis();//用D-C得到一个毫秒值longtime = nowTime - myTime;//把E的毫秒值转换为年longday = time / 1000 / 60 / 60 / 24;System.out.println("你来到这个世界:" + day + "天");}
}

(2)DateFormat针对日期进行格式化和针对字符串进行解析的类,但是是抽象类,所以使用其子类SimpleDateFormat

SimpleDateFormat的构造方法:

                   SimpleDateFormat():                          默认模式

                    SimpleDateFormat(Stringpattern):       给定的模式

                                   yyyy-MM-dd HH:mm:ss

              A:日期和字符串的转换

                     a:Date -- String(格式化)

                            public final Stringformat(Date date)

                           

                     b:String -- Date(解析)

                            public Dateparse(String source)

 

public class DateFormatDemo {publicstatic void main(String[] args) throws ParseException {//Date -- String//创建日期对象Dated = new Date();//创建格式化对象//SimpleDateFormat sdf = new SimpleDateFormat();//给定模式SimpleDateFormatsdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");//public final String format(Date date)Strings = sdf.format(d);System.out.println(s);//String-- DateStringstr = "2008-08-08 12:12:12";//在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配SimpleDateFormatsdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Datedd = sdf2.parse(str);System.out.println(dd);}
}

              B:案例:

                     制作了一个针对日期操作的工具类。

------------------------------------------------------------------------------------------------------------------------------------------

 * 这是日期和字符串相互转换的工具类

 * @author 风清扬

 

public class DateUtil {privateDateUtil() {}/* 这个方法的作用就是把日期转成一个字符串* @param d*           被转换的日期对象* @param format*           传递过来的要被转换的格式* @return 格式化后的字符串 */publicstatic String dateToString(Date d, String format) {//SimpleDateFormat sdf = new SimpleDateFormat(format);//return sdf.format(d);returnnew SimpleDateFormat(format).format(d);}/* 这个方法的作用就是把一个字符串解析成一个日期对象** @param s*           被解析的字符串* @param format*           传递过来的要被转换的格式* @return 解析后的日期对象* @throws ParseException */publicstatic Date stringToDate(String s, String format)throwsParseException {returnnew SimpleDateFormat(format).parse(s);}
}

 

 

 

public class DateUtilDemo {publicstatic void main(String[] args) throws ParseException {Dated = new Date();//yyyy-MM-dd HH:mm:ssStrings = DateUtil.dateToString(d, "yyyy年MM月dd日HH:mm:ss");System.out.println(s);Strings2 = DateUtil.dateToString(d, "yyyy年MM月dd日");System.out.println(s2);Strings3 = DateUtil.dateToString(d, "HH:mm:ss");System.out.println(s3);Stringstr = "2014-10-14";Datedd = DateUtil.stringToDate(str, "yyyy-MM-dd");System.out.println(dd);}
}

8:Calendar日历类(掌握)

       (1)Calendar:它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。。

       (2)成员方法

如何得到一个日历对象呢?

A:public static CalendargetInstance()

Calendar rightNow =Calendar.getInstance();

                                   本质返回的是子类对象

              B: public int get(int field):

返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型。

 

public class CalendarDemo {publicstatic void main(String[] args) {//其日历字段已由当前日期和时间初始化:CalendarrightNow = Calendar.getInstance(); // 子类对象//获取年intyear = rightNow.get(Calendar.YEAR);//获取月intmonth = rightNow.get(Calendar.MONTH);//获取日intdate = rightNow.get(Calendar.DATE);System.out.println(year+ "年" + (month + 1) + "月" + date + "日");}
}
/** abstract class Person { public static PersongetPerson() { return new* Student(); } }* class Student extends Person {* }*/

              C: public void add(int field,intamount)

根据日历字段和一个正负数确定是添加还是减去对应日历字段的值

              D: public final void set(int year,intmonth,int date)

设置日历对象的年月日

 

public class CalendarDemo {publicstatic void main(String[] args) {//获取当前的日历时间Calendarc = Calendar.getInstance();//获取年intyear = c.get(Calendar.YEAR);//获取月intmonth = c.get(Calendar.MONTH);//获取日intdate = c.get(Calendar.DATE);System.out.println(year+ "年" + (month + 1) + "月" + date + "日");三年前的今天//c.add(Calendar.YEAR, -3);获取年//year = c.get(Calendar.YEAR);// // 获取月//month = c.get(Calendar.MONTH);获取日//date = c.get(Calendar.DATE);//System.out.println(year + "年"+ (month + 1) + "月" + date + "日");//5年后的10天前c.add(Calendar.YEAR,5);c.add(Calendar.DATE,-10);//获取年year= c.get(Calendar.YEAR);//获取月month= c.get(Calendar.MONTH);//获取日date= c.get(Calendar.DATE);System.out.println(year+ "年" + (month + 1) + "月" + date + "日");System.out.println("--------------");c.set(2011,11, 11);//获取年year= c.get(Calendar.YEAR);//获取月month= c.get(Calendar.MONTH);//获取日date= c.get(Calendar.DATE);System.out.println(year+ "年" + (month + 1) + "月" + date + "日");}
}

       (3)案例:

              计算任意一年的2月份有多少天?

* 分析:

 *          A:键盘录入任意的年份

 *          B:设置日历对象的年月日

 *                 年就是A输入的数据

 *                 月是2

 *                 日是1

 *          C:把时间往前推一天,就是2月的最后一天

 *          D:获取这一天输出即可

 

public class CalendarTest {publicstatic void main(String[] args) {//键盘录入任意的年份Scannersc = new Scanner(System.in);System.out.println("请输入年份:");intyear = sc.nextInt();//设置日历对象的年月日Calendarc = Calendar.getInstance();c.set(year,2, 1); // 其实是这一年的3月1日//把时间往前推一天,就是2月的最后一天c.add(Calendar.DATE,-1);//获取这一天输出即可System.out.println(c.get(Calendar.DATE));}
}

 

小知识:日期类的时间从为什么是从197011

 

I suspect that Java was born and raised on aUNIX system.

UNIXconsiders the epoch (when did time begin) to be midnight, January 1, 1970.

是说java起源于UNIX系统,而UNIX认为1970年1月1日0点是时间纪元.

但这依然没很好的解释"为什么",出于好奇,继续Google,总算找到了答案:

http://en.wikipedia.org/wiki/Unix_time

 

这里的解释是:

最初计算机操作系统是32位,而时间也是用32位表示。

System.out.println(Integer.MAX_VALUE);

2147483647

Integer在JAVA内用32位表 示,因此32位能表示的最大值是2147483647。

另外1年365天的总秒数是31536000,

2147483647/31536000 = 68.1

也就是说32位能表示的最长时间是68年,而实际上到2038年01月19日03时14分07

秒,便会到达最大时间,过了这个时间点,所有32位操作系统时间便会变为

1000000000000000 00000000 00000000

也就是1901年12月13日20时45分52秒,这样便会出现时间回归的现象,很多软件便会运行异常了。

 

到这里,我想问题的答案已经出来了:

因为用32位来表示时间的最大间隔是68年,而最早出现的UNIX操作系统考虑到计算

机产生的年代和应用的时限综合取了1970年1月1日作为UNIXTIME的纪元时间(开始

时间),而java自然也遵循了这一约束。

至于时间回归的现象相信随着64为操作系统的产生逐渐得到解决,因为用64位操作

系统可以表示到292,277,026,596年12月4日15时30分08秒,相信我们的N代子孙,哪

怕地球毁灭那天都不用愁不够用了,因为这个时间已经是千亿年以后了。

最后一个问题:上面System.out.println(new Date(0)),打印出来的时间是8点而非0点,

原因是存在系统时间和本地时间的问题,其实系统时间依然是0点,只不过我的电脑时区

设置为东8区,故打印的结果是8点。

这篇关于14. 正则表达式和常见类 (Math、Random、System、BigInteger、BigDecimal、Date_DateFormat、Calendar)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/392918

相关文章

嵌入式软件常见的笔试题(c)

找工作的事情告一段落,现在把一些公司常见的笔试题型整理一下,本人主要是找嵌入式软件方面的工作,笔试的也主要是C语言、数据结构,大体上都比较基础,但是得早作准备,才会占得先机。   1:整型数求反 2:字符串求反,字符串加密,越界问题 3:字符串逆序,两端对调;字符串逆序,指针法 4:递归求n! 5:不用库函数,比较两个字符串的大小 6:求0-3000中含有9和2的全部数之和 7

vscode-创建vue3项目-修改暗黑主题-常见错误-element插件标签-用法涉及问题

文章目录 1.vscode创建运行编译vue3项目2.添加项目资源3.添加element-plus元素4.修改为暗黑主题4.1.在main.js主文件中引入暗黑样式4.2.添加自定义样式文件4.3.html页面html标签添加样式 5.常见错误5.1.未使用变量5.2.关闭typescript检查5.3.调试器支持5.4.允许未到达代码和未定义代码 6.element常用标签6.1.下拉列表

Java中的正则表达式使用技巧

Java中的正则表达式使用技巧 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天,我们来探讨一下Java中正则表达式的使用技巧。正则表达式是一种强大的工具,用于字符串匹配、替换和分割等操作。掌握正则表达式能够大大提高我们处理文本数据的效率。 1. 正则表达式的基本概念 正则表达式(Regular Expression,简称

js 正则表达式出现问题

帮同事写个页面,出现正则表达式不管怎么改都没法匹配的情况。。。。 reg = /^sy[0-9]+$/i; if(rtx.match(reg) == null){ alert("请输入正确的RTX账号!"); return false; } 因为之前一直用的是 reg ="/^sy[0-9]+$/i"; 写PHP写习惯了。。外面多写了两个双引号……T.T 改

Linux - 探秘 Linux 的 /proc/sys/vm 常见核心配置

文章目录 PreLinux 的 /proc/sys/vm 简述什么是 /proc/sys/vm?主要的配置文件及其用途参数调整对系统的影响dirty_background_ratio 和 dirty_ratioswappinessovercommit_memory 和 overcommit_ratiomin_free_kbytes 实例与使用建议调整 swappiness设置 min_fr

CS162 Operating System-lecture2

A tread is suspended or no longer executing when its state’s not loaded in registers the point states is pointed at some other thread .so the thread that’s suspended is actually siting in memory and

【大数据 复习】第11,12,13,14章

Web应用与流数据 1.在Web应用、网络监控、传感监测等领域,兴起了一种新的数据密集型应用——静态数据,即数据以大量、快速、时变的流形式持续到达。( )    正确答案: 错误 错误在静态数据,这里应该叫非静态数据之类的,虽然没有这个名词。 2.流数据适合采用批量计算,因为流数据适合用传统的关系模型建模。( )    正确答案: 错误 传统的关系模型一般是用于静态数据的存储和分析,例如 S

C语言常见面试题3 之 基础知识

(1)i++和++i哪个效率更高? 对于内建数据类型,二者效率差别不大(去除编译器优化的影响) 对于自定义数据类型(主要是类),因为前缀式(++i)可以返回对象的引用;而后缀式(i++)必须返回对象的值,所以导致在大对象时产生了较大的复制开销,引起效率降低。 (2)不使用任何中间变量如何交换a b的值? void swap(int& a, int& b)//采用引用传参的方式{a^=

常见兼容性问题集合

* png24位的图片在iE6浏览器上出现背景,解决方案是做成PNG8.也可以引用一段脚本处理.* 浏览器默认的margin和padding不同。解决方案是加一个全局的*{margin:0;padding:0;}来统一。* IE6双边距bug:块属性标签float后,又有横行的margin情况下,在ie6显示margin比设置的大。 * 浮动ie产生的双倍距离(IE6双边距问题:在IE6下,如果对

【JavaSE ⑧】P219 ~ 225 Date类‘’DateFormat类转化Date和字符串;Calendar类获得日历中某值,修改日历,日历转日期

目录 日期时间类1 Date类概述常用方法 2DateFormat类构造方法格式规则常用方法parse方法format方法 3 Calendar类概念获取方式常用方法get/set方法add方法getTime方法 ● 练习1.判断Date不同参数构造的输出2. 用日期时间相关的API,计算一个人已经出生了多少天。3. 获取Calendar对象,输出日历当前年,月,日4. 把日历转换为日期