今天学什么?
一.日期与时间
1.Date
Date类概述
Date类的对象在Java中代表的是当前所在系统此刻日期时间.
Date的构造器
名称 | 说明 |
public Date() | 创建一个Date对象,代表的是系统当前此刻日期时间. |
Date的常用方法
名称 | 说明 |
public long getTime | 获取时间对象的毫秒值 |
package com.wjh2.itwjh.d1_date;
import java.util.Date;
public class DateDemo1 {
/*
学会使用Date类处理时间,获取时间的信息
*/
public static void main(String[] args) {
//1.创建一个Date类对象,代表此刻日期时间对象
Date d= new Date();
System.out.println(d); //Wed Apr 12 19:34:58 CST 2023
//2.获取时间毫秒值
long time = d.getTime();
System.out.println(time);
long time1 = System.currentTimeMillis();
}
}
package com.wjh2.itwjh.d1_date;
import java.util.Date;
public class DateDemo2 {
/*
案例:请计算出当前时间往后走1小时121秒之后的时间是多少.
*/
public static void main(String[] args) {
System.out.println("------------方法一:-------------");
//创建此刻时间对象Date
//1.得到当前时间的毫秒值
Date d1 = new Date();
System.out.println(d1);
//2.当前时间往后走1小时121秒
long time2 = System.currentTimeMillis();
time2 += (60 * 60 +121) * 1000;
Date d2 = new Date(time2); //往里面注入time2时间数
System.out.println(d2);
/*
------------方法一:-------------
Wed Apr 12 19:52:41 CST 2023
Wed Apr 12 20:54:42 CST 2023
*/
System.out.println("------------方法二:-------------");
Date d3 = new Date();
d3.setTime(time2);
System.out.println(d3);
/*
------------方法一:-------------
Wed Apr 12 19:52:41 CST 2023
Wed Apr 12 20:54:42 CST 2023
------------方法二:-------------
Wed Apr 12 20:54:42 CST 2023
*/
}
}
2.SimpleDateFormat
package com.wjh2.itwjh.d2_SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo1 {
/*
目标:SimpleDateFormat简单日期格式化类的使用
格式化时间
解析时间
*/
public static void main(String[] args) {
//1.日期对象
Date d = new Date();
System.out.println(d);
//2.格式化这个日期对象(指定最终格式化的形式)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss:ms EEE a"); //EEE -> 星期几 ; a -> 上午还是下午?
//3.开始格式化日期对象成为喜欢的字符串形式
String rs = sdf.format(d);
System.out.println(rs);
/*
Wed Apr 12 20:13:54 CST 2023
2023年04月12日 20:13:54:1354 周三 下午
*/
System.out.println("-------------");
//4.格式化时间毫秒值
//需求:请问121秒后的时间是多少?
long time1 = System.currentTimeMillis() + 121 * 1000;
String rs2 = sdf.format(time1);
System.out.println(rs2);
/*
-------------
2023年04月12日 20:20:41:2041 周三 下午
*/
System.out.println("-------------解析字符串时间,下个代码--------------");
}
}
package com.wjh2.itwjh.d2_SimpleDateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo2 {
/*
目标:学会使用SimpleDateFormat解析字符串时间成为日期对象
需求:有一个时间2021年08月06日11点11分11秒,往后走2天14小时49分06秒后的时间是多少?
*/
public static void main(String[] args) throws ParseException {
//1.把字符串时间拿到程序中...
String dateStr = "2021年08月06日 11:11:11";
//2.把字符串时间解析成日期对象(本节重点):形式必须与被解析时间的形式完全一样,否则解析会报错!
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d = sdf.parse(dateStr); //parse -> 解析
// ^ -> 提醒:容易出错:Alt+Enter 在main方法生成 throws ParseException
//打印出这个时间
System.out.println(sdf.format(d));
//3.往后走2天14小时49分06秒
long time = d.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6) * 1000;
//4.格式化这个时间毫秒值就是这个结果
System.out.println(sdf.format(time));
/*
2021年08月06日 11:11:11
2021年08月09日 02:00:17
*/
}
}
自己写的:
package com.wjh2.itwjh.d2_SimpleDateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo3 {
/*
小贾下单时间:2020年11月11日 00:03:47
小贾下单时间:2020年11月11日 00:10:11
一元秒杀
开始时间:2020年11月11日 00:00:00
结束时间:2020年11月11日 00:10:00
需求:判断小贾和小明是否参加了秒杀活动?
*/
public static void main(String[] args) throws ParseException {
String StartDateStr = "2020年11月11日 00:00:00";
String EndDateStr = "2020年11月11日 00:10:00";
//小贾
String xj = "2020年11月11日 00:03:47";
//小明
String xm = "2020年11月11日 00:10:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d1 = sdf.parse(StartDateStr);
long time1 = d1.getTime();
System.out.println(time1); //开始时间毫秒值
Date d2 = sdf.parse(EndDateStr); //结束时间毫秒值
long time2 = d2.getTime();
System.out.println(time2);
Date xjDate = sdf.parse(xj); //小贾时间毫秒值
long xjTime = xjDate.getTime();
System.out.println(xjTime);
Date xmDate = sdf.parse(xm); //小明时间毫秒值
long xmTime = xmDate.getTime();
System.out.println(xmTime);
System.out.println("小贾下单时间:" + sdf.format(xjDate));
System.out.println("小明下单时间:" + sdf.format(xmDate));
System.out.println("一元秒杀");
System.out.println("开始时间:" + sdf.format(d1));
System.out.println("结束时间:" + sdf.format(d2));
if(xjTime >= time1 && xjTime<= time2){
System.out.println("小贾参加了秒杀活动");
}else{
System.out.println("小贾没有参加秒杀活动");
}
if(xmTime >= time1 && xmTime<= time2){
System.out.println("小明参加了秒杀活动");
}else{
System.out.println("小明没有参加秒杀活动");
}
/*
1605024000000 -> 开始
1605024600000 -> 结束
1605024227000 -> 小贾
1605024611000 -> 小明
小贾下单时间:2020年11月11日 00:03:47
小明下单时间:2020年11月11日 00:10:11
一元秒杀
开始时间:2020年11月11日 00:00:00
结束时间:2020年11月11日 00:10:00
小贾参加了秒杀活动
小明没有参加秒杀活动
进程已结束,退出代码为 0
*/
}
}
简化:
package com.wjh2.itwjh.d2_SimpleDateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo3 {
/*
小贾下单时间:2020年11月11日 00:03:47
小明下单时间:2020年11月11日 00:10:11
一元秒杀
开始时间:2020年11月11日 00:00:00
结束时间:2020年11月11日 00:10:00
需求:判断小贾和小明是否参加了秒杀活动?
*/
public static void main(String[] args) throws ParseException {
//1.开始 和 结束时间
String StartDateStr = "2020年11月11日 00:00:00";
String EndDateStr = "2020年11月11日 00:10:00";
//2.小贾 和 小明
String xj = "2020年11月11日 00:03:47";
String xm = "2020年11月11日 00:10:11";
//3.解析他们的时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d1 = sdf.parse(StartDateStr);
Date d2 = sdf.parse(EndDateStr);
Date d3 = sdf.parse(xj);
Date d4 = sdf.parse(xm);
if(d3.after(d1) && d3.before(d2)){
System.out.println("小贾参加了活动");
}else{
System.out.println("小贾没有参加活动");
}
if(d4.after(d1) && d4.before(d2)){
System.out.println("小明参加了活动");
}else{
System.out.println("小明没有参加活动");
}
/*
小贾参加了活动
小明没有参加活动
*/
/*
新用法:
判断一个Date是否在另一个Date之前或者之后可以用:
newDate.after(oldDate)
newDate.before(oldDate)
*/
}
}
3.Calendar
package com.wjh2.itwjh.d2_SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarDemo1 {
public static void main(String[] args) {
//1.拿到系统此刻日期对象
Calendar cal = Calendar.getInstance();
System.out.println(cal);
//2.获取日历的信息
int year = cal.get(Calendar.YEAR);
System.out.println(year);
int month = cal.get(Calendar.MONTH) + 1; //月份需要 +1
System.out.println(month);
int day = cal.get(Calendar.DAY_OF_MONTH); //当月第几天
System.out.println(day);
int day1 = cal.get(Calendar.DAY_OF_YEAR); //当年第几天
System.out.println(day1);
//3.public void set(int field,int value);修改日历的某个字段信息.
//cal.set(Calendar.HOUR,12); //一般不修改
//System.out.println(cal);
//4.public void add(int field,int value);为某个字段增加/减少指定值.
//请问64天后是什么时间
cal.add(Calendar.DAY_OF_YEAR,64);
cal.add(Calendar.MINUTE,64);
System.out.println(cal);
// int day64 = cal.get(Calendar.DAY_OF_YEAR) + 64;
// System.out.println(day64);
//5.public final Date getTime(); 拿到此刻日期对象.
Date d = cal.getTime();
System.out.println(d);
//6.public long getTimeImMillis(); 拿到此刻时间毫秒值.
long time = cal.getTimeInMillis();
System.out.println(time);
/*
java.util.GregorianCalendar[time=1681309995110,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2023,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=3,DAY_OF_MONTH=12,DAY_OF_YEAR=102,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=33,SECOND=15,MILLISECOND=110,ZONE_OFFSET=28800000,DST_OFFSET=0]
2023
4
12
102
java.util.GregorianCalendar[time=1686843435110,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2023,MONTH=5,WEEK_OF_YEAR=24,WEEK_OF_MONTH=3,DAY_OF_MONTH=15,DAY_OF_YEAR=166,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=11,HOUR_OF_DAY=23,MINUTE=37,SECOND=15,MILLISECOND=110,ZONE_OFFSET=28800000,DST_OFFSET=0]
Thu Jun 15 23:37:15 CST 2023
1686843435110
进程已结束,退出代码为 0
*/
}
}
二.JDK8新增日期类
1.概述,LocalTime / LocalDate / LocalDateTime
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.LocalDate;
import java.time.Month;
public class Demo01LocalDate {
public static void main(String[] args) {
//1.获取本地日期对象.
LocalDate nowDate =LocalDate.now();
System.out.println("今天的日期是:" + nowDate);
int year = nowDate.getYear();
System.out.println("年:" + year);
int month = nowDate.getMonthValue();
System.out.println("月:" + month);
int day= nowDate.getDayOfMonth();
System.out.println("日:" + day);
//一年中第几天
int YDay = nowDate.getDayOfYear();
System.out.println("一年中第" + YDay + "天");
System.out.println("距离元旦还有" + (365-YDay) + "天");
//星期几?
System.out.println(nowDate.getDayOfWeek());
System.out.println(nowDate.getDayOfWeek().getValue()); //getValue 转化为 int 类型
//月份
System.out.println(nowDate.getMonth());
System.out.println(nowDate.getMonth().getValue());
System.out.println("-------------------");
LocalDate birthday = LocalDate.of(2000,1,29);
System.out.println(birthday); //直接传入对应的年月日
System.out.println(LocalDate.of(2000, Month.JANUARY,29));
}
}
今天的日期是:2023-04-26
年:2023
月:4
日:26
一年中第116天
距离元旦还有249天
WEDNESDAY
3
APRIL
4
-------------------
2000-01-29
2000-01-29进程已结束,退出代码为 0
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
public class Demo02LocalDate {
public static void main(String[] args) {
//1.获取本地时间对象
LocalTime nowTime = LocalTime.now();
System.out.println("今天的时间是:" + nowTime); //今天的时间
int hour = nowTime.getHour(); //时
System.out.println("小时:" + hour);
int minute = nowTime.getMinute(); //分
System.out.println("分钟:" + minute);
int second = nowTime.getSecond(); //秒
System.out.println("秒:" + second);
int nano = nowTime.getNano(); //纳秒
System.out.println("纳秒:" + nano);
System.out.println("--------");
System.out.println(LocalTime.of(9,45)); //时分
System.out.println(LocalTime.of(9,45,30)); //时分秒
System.out.println(LocalTime.of(9,45,30,22));//时分秒纳秒
System.out.println("--------");
System.out.println(LocalDateTime.of(2000,1,29,10,20)); //年月日时分
System.out.println(LocalDateTime.of(2000, Month.JANUARY,29,10,30)); //枚举 (下同)
System.out.println(LocalDateTime.of(2000,1,29,10,20,56)); //年月日时分秒
System.out.println(LocalDateTime.of(2000, Month.JANUARY,29,10,30,56));
System.out.println(LocalDateTime.of(2000,1,29,10,20,56,20)); //年月日时分秒纳秒
System.out.println(LocalDateTime.of(2000, Month.JANUARY,29,10,30,56,20));
}
}
今天的时间是:10:00:17.553425600
小时:10
分钟:0
秒:17
纳秒:553425600
--------
09:45
09:45:30
09:45:30.000000022
--------
2000-01-29T10:20
2000-01-29T10:30
2000-01-29T10:20:56
2000-01-29T10:30:56
2000-01-29T10:20:56.000000020
2000-01-29T10:30:56.000000020进程已结束,退出代码为 0
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.LocalDate;
import java.time.LocalTime;
public class Demo04LocalDate {
public static void main(String[] args) {
LocalTime nowTime = LocalTime.now();
System.out.println(nowTime); //当前时间
System.out.println(nowTime.minusHours(1)); //一小时前
System.out.println(nowTime.minusMinutes(1)); //一分钟前
System.out.println(nowTime.minusSeconds(1)); //一秒钟前
System.out.println(nowTime.minusNanos(1)); //一纳秒钟前
System.out.println("------------");
System.out.println(nowTime.plusHours(1)); //一小时后
System.out.println(nowTime.plusMinutes(1)); //一分钟后
System.out.println(nowTime.plusSeconds(1)); //一秒钟后
System.out.println(nowTime.plusNanos(1)); //一纳秒后
System.out.println("-----------");
System.out.println(nowTime); //与原始值一致
//不可变对象,上面对时间处理产生的是新对象,所以不会改变nowTime新对象的值
LocalDate myDate = LocalDate.of(2023,7,29);
LocalDate nowDate = LocalDate.now();
System.out.println("今天是公主的生日吗?");
if (myDate.equals(nowDate)){
System.out.println("今天是公主的生日,记得准备好礼物噢");
} else {
System.out.println("今天不是公主的生日,不要心急哈,距离公主的生日还有" + (myDate.getDayOfYear() - nowDate.getDayOfYear()) + "天");
}
System.out.println("今天是公主的生日吗?" + nowDate.equals(myDate));
System.out.println(myDate + "是否在" + nowDate + "之前" + myDate.isBefore(nowDate));
// 日期一.isBefore(日期二) -> 日期一是否在日期二之前???
System.out.println(myDate + "是否在" + nowDate + "之后" + myDate.isAfter(nowDate));
// 日期一.isAfter(日期二) -> 日期一是否在日期二之后???
//判断今天是否是你的生日
LocalDate birDate = LocalDate.of(2000,1,29);
LocalDate nowDate1 = LocalDate.now();
MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());
MonthDay nowMd = MonthDay.from(nowDate1);
System.out.println("今天是你的生日吗?" + birMd.equals(nowMd)); //今天是你的生日吗?
}
}
10:38:44.034896
09:38:44.034896
10:37:44.034896
10:38:43.034896
10:38:44.034895999
------------
11:38:44.034896
10:39:44.034896
10:38:45.034896
10:38:44.034896001
-----------
10:38:44.034896
今天是公主的生日吗?
今天不是公主的生日,不要心急哈,距离公主的生日还有92天
今天是公主的生日吗?false
2023-07-29是否在2023-04-28之前false
2023-07-29是否在2023-04-28之后true进程已结束,退出代码为 0
2.instant
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
public class Demo05Instant {
public static void main(String[] args) {
//1.得到一个Instant时间戳对象
Instant instant = Instant.now();
System.out.println(instant);
//2.系统此刻的时间戳怎么办?
Instant instant1 = Instant.now();
//把时间戳调到系统默认的时区
System.out.println(instant1.atZone(ZoneId.systemDefault()));
//3.如何去返回Date对象
Date date = Date.from(instant);
System.out.println(date);
Instant i2 = date.toInstant();
System.out.println(i2);
}
}
2023-04-28T03:03:58.725521800Z
2023-04-28T11:03:58.730532700+08:00[Asia/Shanghai]
Fri Apr 28 11:03:58 CST 2023
2023-04-28T03:03:58.725Z进程已结束,退出代码为 0
3.DateTimeFormat
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo06DateTimeFormat {
public static void main(String[] args) {
//本地此刻 日期时间 对象
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
//解析/格式化器
DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");
DateTimeFormatter dftCH = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒 EEE a");
//正向格式化
String ldtString1 = dft.format(ldt);
System.out.println(ldtString1); //2023-04-08 11:15:55 周五 上午
String ldtString2 = dftCH.format(ldt);
System.out.println(ldtString2); //2023年04月28日 11时23分41秒 周五 上午
//逆向格式化
String ldtString = ldt.format(dft);
System.out.println(ldtString); //2023-04-28 11:17:29 周五 上午
//解析字符串时间
DateTimeFormatter dft1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateStr = "2019-09-07 10:20:30";
//解析当前字符串时间成为本地日期时间对象
LocalDateTime ldt1 = LocalDateTime.parse(dateStr , dft1);
System.out.println(ldt1);
}
}
2023-04-28T11:23:41.756555700
2023-04-28 11:23:41 周五 上午
2023年04月28日 11时23分41秒 周五 上午
2023-04-28 11:23:41 周五 上午
2019-09-07T10:20:30进程已结束,退出代码为 0
4.Duration / Period
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.LocalDate;
import java.time.Period;
public class Demo06period {
public static void main(String[] args) {
//当前本地 年月日
LocalDate today = LocalDate.now();
System.out.println(today);
//生日前 年月日
LocalDate birthday = LocalDate.of(2000,1,29);
System.out.println(birthday);
Period period = Period.between(birthday, today); //第二个参数减第一个参数
System.out.println(period.getYears()); //23
System.out.println(period.getMonths()); //2
System.out.println(period.getDays()); //30
}
}
2023-04-28
2000-01-29
23
2
30进程已结束,退出代码为 0
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Demo08Duration {
public static void main(String[] args) {
//本地日期时间对象
LocalDateTime today = LocalDateTime.now();
System.out.println(today);
//出生的日期时间对象
LocalDateTime birthday = LocalDateTime.of(2000,1,29,13,14,52);
System.out.println(birthday);
Duration duration = Duration.between(birthday, today); //第二个参数减第一个参数
System.out.println(duration.toDays()); //两个时间差的天数
System.out.println(duration.toHours()); //两个时间差的小时数
System.out.println(duration.toMinutes()); //两个时间差的分钟数
System.out.println(duration.toMillis()); //两个时间差的毫秒数
System.out.println(duration.toNanos()); //两个时间差的纳秒数
}
}
2023-04-28T11:53:16.982916100
2000-01-29T13:14:52
8489
203758
12225518
733531104982
733531104982916100进程已结束,退出代码为 0
5.ChronoUnit
package com.wjh2.itwjh.d4_JDK8_time;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class Demo09ChronoUnit {
public static void main(String[] args) {
//本地日期时间: 本地的
LocalDateTime today = LocalDateTime.now();
System.out.println(today);
//生日时间
LocalDateTime birthday = LocalDateTime.of(2000,1,29,13,14,52);
System.out.println(birthday);
//第二个参数减第一个参数
System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthday, today));
System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthday, today));
System.out.println("相差的日数:" + ChronoUnit.DAYS.between(birthday, today));
System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthday, today));
System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthday, today));
System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthday, today));
System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthday, today));
System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthday, today));
System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthday, today));
System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthday, today));
System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthday, today));
System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthday, today));
System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthday, today));
}
}
2023-04-28T12:06:25.704122900
2000-01-29T13:14:52
相差的年数:23
相差的月数:278
相差的日数:8489
相差的时数:203758
相差的分数:12225531
相差的秒数:733531893
相差的毫秒数:733531893704
相差的微秒数:733531893704122
相差的纳秒数:733531893704122900
相差的半天数:16979
相差的十年数:2
相差的世纪(百年)数:0
相差的千年数:0进程已结束,退出代码为 0
三.包装类
package com.wjh2.itwjh.d5_integer;
/*
目标:明白包装类的概念,并使用
*/
public class Test {
public static void main(String[] args) {
int a = 10;
Integer a1 = 11;
Integer b1= a; //自动装箱
System.out.println(b1);
int b = b1; //自动拆箱
System.out.println(b);
System.out.println(a);
System.out.println(a1);
System.out.println("-----------");
double d = 99.5;
Double d1 = d; //自动装箱
System.out.println(d1);
double e = d1; //自动拆箱
System.out.println(e);
System.out.println("----------");
//int age = null; 报错! -> int是引用类型 不能接null
Integer age1 = null;
Integer age2 = 0;
System.out.println(age1);
System.out.println(age2);
System.out.println("------(没用篇)------");
//1.包装类可以把基本类型的数据转换成字符串的形式(没用)
Integer ages = 23;
String rs = ages.toString();
String rs1 = Integer.toString(ages);
System.out.println(rs + 1);
System.out.println(rs1 + 1);
//可以直接+字符串得到字符串类型
String rs2 = ages + "";
System.out.println(rs2 + 1);
System.out.println("------(非常有用篇)------");
String number = "23";
//转换成整数
int Mage = Integer.parseInt(number);
System.out.println(Mage + 1);
String number2 = "99.5";
//转换成小数
double Mage2 =Double.parseDouble(number2);
System.out.println(Mage2 + 0.5);
//parse不好用,可以用 类型.ValueOf()
String number3 = "23";
int Mage3 = Integer.valueOf(number3);
System.out.println(Mage3 + 1);
String number4 = "88.8";
double Mage4 = Double.valueOf(number4);
System.out.println(Mage4 + 0.2);
//记住 类型.ValueOf() 即可!
//作用:将字符串类型转换成真实数据类型
//细节: 将字符串类型转换成真实数据的时候,假如原始字符串是:23.aaa 此时不能转换成真实数据
// --> 小数转整数也是不能转的,必须是对应类型才能转换,但是整数可以转换成小数
}
}
10
10
10
11
-----------
99.5
99.5
----------
null
0
------(没用篇)------
231
231
231
------(非常有用篇)------
24
100.0
24
89.0进程已结束,退出代码为 0
四.正则表达式
1.正则表达式概述,初体验
原始方法:
package com.wjh2.itwjh.d6.regex;
import java.util.Scanner;
public class RegexDemo1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//需求:校验QQ号是否正确:必须全是数字,且长度在6-20位
while (true){
System.out.println("请输入您的QQ号:");
String bo = sc.next();
boolean bo1 = checkQQ(bo);
String ch = (bo1 == true) ? "合法" : "不合法";
System.out.println(ch);
}
}
public static boolean checkQQ(String qq){
//1.判断QQ号的长度是否满足要求
if(qq == null || qq.length() < 6 || qq.length() > 20){
return false;
}
//2.判断qq是否全部是数字,不是返回false
// 18231a79657
for (int i = 0; i < qq.length(); i++) {
//获取每一位字符
char ch = qq.charAt(i);
//判断这个字符是否不是数字,不是数字直接返回false
if(ch < '0' || ch > '9'){
return false;
}
}
return true; //合法QQ号
}
}
请输入您的QQ号:
1
不合法
请输入您的QQ号:
2
不合法
请输入您的QQ号:
182
不合法
请输入您的QQ号:
1kk
不合法
请输入您的QQ号:
182317
合法
请输入您的QQ号:
182317a
不合法
请输入您的QQ号:
1823179657
合法
请输入您的QQ号:
1823179657a
不合法
请输入您的QQ号:
11234695
合法
请输入您的QQ号:
sss555sss555
不合法
请输入您的QQ号:
正则表达式:
package com.wjh2.itwjh.d6.regex;
import java.util.Scanner;
public class RegexDemo1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//需求:校验QQ号是否正确:必须全是数字,且长度在6-20位
//正则表达式出体验:
System.out.println("正则表达式:请输入您的QQ号:");
String boo = sc.next();
boolean boo1 = checkQQ2(boo);
String chh = (boo1 == true) ? "合法" : "不合法";
System.out.println(chh);
}
}
/*
.matches(regex:)
\ -> 特殊字符,比较敏感
\d -> 反斜杠d表示全部是数字
\\d -> 转义:
有两个反斜杠表示:第一个斜杆告诉第二个斜杠你就是杠
*/
public static boolean checkQQ2(String qq){
return qq != null && qq.matches("\\d{6,20}");
}
}
}
正则表达式:请输入您的QQ号:
1
不合法
正则表达式:请输入您的QQ号:
182
不合法
正则表达式:请输入您的QQ号:
182317
合法
正则表达式:请输入您的QQ号:
1
不合法
正则表达式:请输入您的QQ号:
6
不合法
正则表达式:请输入您的QQ号:
555
不合法
正则表达式:请输入您的QQ号:
182318
合法
正则表达式:请输入您的QQ号:
165g65h6
不合法
正则表达式:请输入您的QQ号:
656fd6
不合法
正则表达式:请输入您的QQ号:
简化了代码......
2.正则表达式的匹配规则
package com.wjh2.itwjh.d6.regex;
/*
目标:全面,深入学习正则表达式的规则
*/
public class RegexDemo2 {
public static void main(String[] args) {
//public boolean matches(String regex); 判断是否与正则表达式匹配,匹配返回true
//只能是a b c
System.out.println("只能是a b c");
System.out.println("a".matches("[abc]")); //ture
System.out.println("z".matches("[abc]")); //false
//不能出现a b c
System.out.println("不能出现a b c");
System.out.println("a".matches("[^abc]")); //false
System.out.println("z".matches("[^abc]")); //true
System.out.println("-----------");
System.out.println("a".matches("\\d")); //false
System.out.println("3".matches("\\d")); //true
System.out.println("333".matches("\\d")); //false
System.out.println("z".matches("\\w")); //true
System.out.println("2".matches("\\w")); //true
System.out.println("21".matches("\\w")); //false
System.out.println("你".matches("\\w")); //false
System.out.println("以上只能校验单个字符");
//校验密码
//必须是数字 字母 下划线 至少6位
System.out.println("ssds3c".matches("\\w{6,}")); //true
System.out.println("ssdsc".matches("\\w{6,}")); //false
System.out.println("ssddsdsda232你sss".matches("\\w{6,}")); //false
System.out.println("---------");
//验证码: 必须是数字和字符 必须4位
System.out.println("23dF".matches("[a-zA-Z0-9]{4,}")); //true
System.out.println("23_F".matches("[a-zA-Z0-9]{4,}")); //false
System.out.println("23dF".matches("[\\w&&[^_]]{4,}")); //true
System.out.println("23_F".matches("[\\w&&[^_]]{4,}")); //false
}
}
只能是a b c
true
false
不能出现a b c
false
true
-----------
false
true
false
true
true
false
false
以上只能校验单个字符
true
false
false
---------
true
false
true
false
3.正则表达式的常见案例
package com.wjh2.itwjh.d6.regex;
import java.util.Scanner;
public class RegexDemo3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//校验手机号码格式
checkPhone(sc);
//校验邮箱格式
checkEmail(sc);
//校验电话
checkTel(sc);
//校验金额
checkMoney(sc);
}
/**
*校验手机号码格式是否正确
*/
public static void checkPhone(Scanner sc){
while(true){
System.out.println("请输入您的手机号码:");
String phoneNumber = sc.next();
//判断手机号码的格式是否正确
if(phoneNumber.matches("1[3-9]\\d{9}")){
System.out.println("手机号码格式正确!");
break;
}else{
System.out.println("手机号码格式错误,请重新输入!");
}
}
}
/**
* 校验邮箱格式是否正确
*/
public static void checkEmail(Scanner sc) {
while (true){
System.out.println("请输入您的邮箱:");
String email = sc.next();
//判断邮箱格式是否正确
if (email.matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-z0-9]{2,5}){1,2}")) {
System.out.println("邮箱格式正确!");
break;
} else {
System.out.println("邮箱格式错误,请重新输入!");
}
}
}
/**
* 校验电话号码格式是否正确
*/
public static void checkTel(Scanner sc) {
while (true){
System.out.println("请输入您的电话:");
String tel = sc.next();
//判断邮箱格式是否正确 020-5348197 0205348197
if (tel.matches("0\\d{2,6}-?\\d{5,20}")) {
System.out.println("电话号码格式正确!");
break;
} else {
System.out.println("电话号码格式错误,请重新输入!");
}
}
}
/**
* 校验金额格式是否正确
*/
public static void checkMoney(Scanner sc) {
while (true){
System.out.println("请输入您的金额:");
String money = sc.next();
//判断邮箱格式是否正确 0.3 99 99.5 100 123.65
//03.31.3
if (money.matches("[1-9]{1,}(\\.\\d{1,2})?")) {
System.out.println("金额格式正确!");
break;
} else {
System.out.println("金额格式错误,请重新输入!");
}
}
}
}
4.正则表达式在方法中的应用
package com.wjh2.itwjh.d6.regex;
/*
目标:正则表达式在方法中的应用.
public String[] split(String regex):
--按照正则表达式匹配的内容进行分割字符串,返回一个字符串数组.
public String replaceAll(String regex,String nextStr):
--按照正则表达式匹配的内容进行替换
*/
public class RegexDemo4 {
public static void main(String[] args) {
String names = "小蓉dsgjhdk666h蓉儿sdsfgh656j65k过儿";
String[] arr = names.split("\\w+");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("---------------");
String names2 = names.replaceAll("\\w+"," ");
System.out.println(names2);
}
}
小蓉
蓉儿
过儿
---------------
小蓉 蓉儿 过儿进程已结束,退出代码为 0
5.正则表达式爬取信息
package com.wjh2.itwjh.d6.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo5 {
public static void main(String[] args) {
String rs = "以前我认为:我只喜欢fff合适的18231796561,但是相处之后,我感觉我们并不合适,虽然efd我知道" +
"世界上根本没f有完全合适的两s个f人只是不想一起磨合15270831315的借口罢了.我们都d不能像以前ggggg一样获得新鲜感," +
"现在剩下的都123456@qq.com是徘wwee徊在撮sssssdddddd合与fffff将就之间,我不想sdf样,但是sdf我们好像都fd做不到了.其实吧,你对我来说" +
"是一个sd沉寂在我心545中的一份愧疚,s三dddd年前ggh的事sdad直让我无法释sadf怀,不是那d份错过dsf的566恋爱,而是你经历的沙场,"
"差几f分就sd得的战场,再加上朋400-682-f5678友的忽然离开,一定很绝望吧,我能体会到这种感觉,但是今天又一次让你经历战场" +
"你也上岸了,as,我sssdfffggwe只希望你14234695212能快乐一点";
//需求:从上面内容中爬取电话号码 邮箱 和手机号码
//1.定义爬取规则
String regex = "(\\w{1,}@\\w{2,10}(\\.\\w{2,10}){1,2})|" +
"(1[3-9]\\d{9})|(0\\d{2,5}-?\\d{5,15})|400-?\\d{3,8}-?\\d{3,8}";
//2.编译正则表达式成为一个匹配规则对象
Pattern pattern = Pattern.compile(regex);
//3.通过匹配规则对象得到一个匹配数据内容的匹配器对象
Matcher matcher = pattern.matcher(rs);
//4.通过匹配器去内容中爬取信息
while(matcher.find()){
System.out.println(matcher.group());
}
}
}
18231796561
15270831315
123456@qq.com
400-682-5678
14234695212进程已结束,退出代码为 0
五.Arrays类
1.Arrays类概述,常用功能演示
package com.wjh2.itwjh.d7_arrays;
import java.util.Arrays;
public class ArrayDemo1 {
public static void main(String[] args) {
//目标:学会使用Arrays类的常用API,并理解其原理
int[] arr = {10, 2, 55, 23, 24, 100};
System.out.println(arr);
//1.返回数组内容的 toString(数组)
String rs = Arrays.toString(arr);
System.out.println(rs);
System.out.println(Arrays.toString(arr));
//2.排序的API(默认对数组元素进行升序排序)
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); //我是API调用工程师
//3.二分搜索技术(前提是数组必须排好序,否则出bug)
int index = Arrays.binarySearch(arr,55);
System.out.println(index);
//返回不存在元素的规律: - (应该插入的位置索引 + 1)
int index2 = Arrays.binarySearch(arr,22);
System.out.println(index2);
//数组如果没有排好序,可能会找不到存在的元素,从而出现bug
}
}
[I@4eec7777
[10, 2, 55, 23, 24, 100]
[10, 2, 55, 23, 24, 100]
[2, 10, 23, 24, 55, 100]
-3进程已结束,退出代码为 0
2.Arrays类对于Comparator比较器的支持
package com.wjh2.itwjh.d7_arrays;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysDemo2 {
public static void main(String[] args) {
//目标:自定义数组的排序规则
//1.Arrays对于sort方法对于默认有值特性的数组是升序排序
int[] ages = {34, 12, 42, 23};
Arrays.sort(ages);
System.out.println(Arrays.toString(ages));
//2.需求:降序排序(自定义比较器对象,只能支持引用类型的排序!!)
Integer[] ages1 = {34, 12, 42, 23};
/*
参数一:被排序的数组,必须引用类型元素
参数二:匿名内部类对象,代表了一个比较器对象.
*/
Arrays.sort(ages1, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// //制定比较规则
// if(o1 > o2){
// return -1;
// }else if(o1 < o2){
// return 1;
// }
// return 0;
// }
//return o1 - o2; //默认升序
return o2 - o1; //降序
}
});
System.out.println(Arrays.toString(ages1));
System.out.println("--------------------");
Student[] students = new Student[3];
students[0] = new Student("吴磊",23,185.5);
students[1] = new Student("胡歌",38,184.5);
students[2] = new Student("靳东",40,183.5);
System.out.println(Arrays.toString(students));
//Arrays.sort(students); 直接排序运行会导致崩溃
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//自己制定比较规则
//return o2.getAge()-o1.getAge(); //按照年龄进行升序排序
//注意:double类型不能直接,而是需要 -> 比较浮点型可以这样写
return Double.compare(o2.getHeight(), o1.getHeight());
}
});
System.out.println(Arrays.toString(students));
}
}
[12, 23, 34, 42]
[42, 34, 23, 12]
--------------------
[Student{name='吴磊', age=23, height=185.5}, Student{name='胡歌', age=38, height=184.5}, Student{name='靳东', age=40, height=183.5}]
[Student{name='靳东', age=40, height=183.5}, Student{name='胡歌', age=38, height=184.5}, Student{name='吴磊', age=23, height=185.5}]进程已结束,退出代码为 0
六.常见算法
1.选择排序
package com.wjh2.itwjh.d8_sortbinarysearch;
import java.util.Arrays;
/*
目标:学会使用排序的方法对数组进行排序
*/
public class Test1 {
public static void main(String[] args) {
//1.定义数组
int[] arr = {5, 1, 3, 2};
//2.定义一个循环控制选择几轮: arr.length - 1
for (int i = 0; i < arr.length - 1 ; i++) {
//i = 0 j = 1 2 3
//i = 1 j = 2 3
//i = 2 j = 3
//3.定义内部循环,控制选择几次
for (int j = i + 1; j < arr.length; j++) {
//当前位: arr[i]
//如果有比当前位数据更小的,则交换
if(arr[i] > arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr)); //[1, 2, 3, 5]
}
}
[1, 2, 3, 5]
进程已结束,退出代码为 0
2.二分查找
package com.wjh2.itwjh.d8_sortbinarysearch;
/*
目标:理解二分查找的原理并实现
*/
public class Test2 {
public static void main(String[] args) {
//1.定义数组
int[] arr = {10, 14, 16, 25, 28, 30, 35, 88, 100};
System.out.println(binarySearch(arr, 100));
}
/**
* 二分查找算法的实现
* @param arr 排序的数组
* @param date 要找的数据
* @return 索引,如果元素存在,直接返回-1
*/
public static int binarySearch(int[] arr,int date){
//1.定义左边位置 和 右边位置
int left = 0;
int right = arr.length - 1;
//2.开始循环,折半查询
while(left <= right){
//取中间索引
int middleIndex = (left + right) / 2;
//3.判断当前中间位置的元素和要找的元素大小情况
if(date > arr[middleIndex]){
//往右边找,左位置更新为 = 中间索引 + 1
left = middleIndex + 1;
}else if(date < arr[middleIndex]){
//往左边找,右边位置 = 中间索引 - 1
right = middleIndex - 1;
}else{
return middleIndex;
}
}
return -1; //查无此元素
}
}
8
进程已结束,退出代码为 0
七.Lambda表达式枚举
1.Lambda概述
package com.wjh2.itwjh.d9_lambda;
public class LambdaDemo2 {
public static void main(String[] args) {
//目标:学会使用Lambda的标准格式简化匿名内部类的代码形式
//Lambda只能简化接口中只有一个抽象方法的匿名内部类形式
// Swimming s = new Swimming() {
// @Override
// public void swim() {
// System.out.println("老师游泳很棒!!!");
// }
// };
//简化代码 ->
Swimming s1 = () -> {
System.out.println("老师游泳很棒!!!");
};
go(s1);
System.out.println("----------------");
//继续简化
go(() -> {
System.out.println("老师游泳很棒!!!");
});
}
public static void go(Swimming s){
System.out.println("start...");
s.swim();
System.out.println("end...");
}
}
@FunctionalInterface //一旦加上这个注解必须是函数式接口,里面只能有一个抽象方法
interface Swimming{
void swim();
}
start...
老师游泳很棒!!!
end...
----------------
start...
老师游泳很棒!!!
end...进程已结束,退出代码为 0
2.Lambda实战-简化常用函数式接口
package com.wjh2.itwjh.d9_lambda;
import com.wjh2.itwjh.d7_arrays.Student;
import java.util.Arrays;
import java.util.Comparator;
public class LambdaDemo3 {
public static void main(String[] args) {
Integer[] ages1 = {34, 12, 42, 23};
/*
参数一:被排序的数组,必须引用类型元素
参数二:匿名内部类对象,代表了一个比较器对象.
*/
// Arrays.sort(ages1, new Comparator<Integer>() {
// @Override
// public int compare(Integer o1, Integer o2) {
// return o2 - o1; //降序
// }
// });
Arrays.sort(ages1,(Integer o1,Integer o2) ->{
return o2 - o1;
});
System.out.println(Arrays.toString(ages1));
}
}
[42, 34, 23, 12]
进程已结束,退出代码为 0