对应PDF已在资源内,自提
一、四种权限修饰符
一、四种权限修饰符
1.参数传递
1.1 类名作为形参和返回值(应用)
1、类名作为方法的形参
方法的形参是类名,其实需要的是该类的对象
实际传递的是该对象的【地址值】
2、类名作为方法的返回值
方法的返回值是类名,其实返回的是该类的对象
实际传递的,也是该对象的【地址值】
public class Cat {
public void eat(){
System.out.println("猫吃鱼");
}
}
public class CatOperator {
public void useCat(Cat c){//Cat c = new Cat();
c.eat();
}
public Cat getCat(){
Cat c=new Cat();
return c;
}
}
public class demo {
public static void main(String[] args) {
//创建操作类对象,并调用方法
CatOperator co=new CatOperator();
Cat c=new Cat();
co.useCat(c);
System.out.println("========");
Cat c2=co.getCat();//new Cat()
c2.eat();
}
}
1.2 抽象类作为形参和返回值(理解)
抽象类作为形参和返回值
方法的形参是抽象类名,其实需要的是该抽象类的子类对象
方法的返回值是抽象类名,其实返回的是该抽象类的子类对象
public abstract class Animal {
public abstract void eat();
}
public class Cat extends Animal{
@Override
public void eat(){
System.out.println("猫吃鱼");
}
}
public class AnimalOperator {
public void useAnimal(Animal a){//Animal a=new Cat();
a.eat();
}
public Animal getAnimal(){
Animal a=new Cat();
return a;
}
}
public class demo02 {
public static void main(String[] args) {
//创建操作类对象,并调用方法
AnimalOperator ao=new AnimalOperator();
Animal a=new Cat();
ao.useAnimal(a);
Animal s2=ao.getAnimal();//new Cat()
s2.eat();
}
}
1.3 接口名作为形参和返回值(理解)
接口作为形参和返回值
方法的形参是接口名,其实需要的是该接口的实现类对象
方法的返回值是接口名,其实返回的是该接口的实现类对象
public interface Jump { void jump(); }
public class JumpOperator { public void useJump(Jump j){//Jump j=new Cat(); j.jump(); } public Jump getJump(){ Jump j=new Cat(); return j; } }
public class Cat implements Jump{ @Override public void jump(){ System.out.println("猫跳高"); } }
public class demo { public static void main(String[] args) { //创建操作类对象,并调用方法 JumpOperator jo=new JumpOperator(); Jump j=new Cat(); jo.useJump(j); Jump j1=new Cat();//new Cat(); j1.jump(); } }
2. 内部类
2.1 内部类的基本使用(理解)
内部类概念
在一个类中定义一个类。举例:在一个类A的内部定义一个类B,类B就被称为内部类
内部类定义格式
格式&举例:
/* 格式: class 外部类名{ 修饰符 class 内部类名{ } } */ class Outer { public class Inner { } }
内部类的访问特点
内部类可以直接访问外部类的成员,包括私有
外部类要访问内部类的成员,必须创建对象
/*
内部类访问特点:
内部类可以直接访问外部类的成员,包括私有
外部类要访问内部类的成员,必须创建对象
*/
public class Outer { private int num=10; //内部类可以直接访问外部类的成员,包括私有 public class Inner{ public void show(){ System.out.println(num); } } //外部类要访问内部类的成员,必须创建对象 public void method(){ //show(); Inner i=new Inner(); i.show(); } }
2.2 成员内部类(理解)
成员内部类的定义位置
在类中方法,跟成员变量是一个位置
外界创建成员内部类格式
格式:外部类名.内部类名 对象名 = 外部类对象.内部类对象;
举例:Outer.Inner oi = new Outer().new Inner();
成员内部类的推荐使用方案
将一个类,设计为内部类的目的,大多数都是不想让外界去访问,所以内部类的定义应该私有化,私有 化之后,再提供一个可以让外界调用的方法,方法内部创建内部类对象并调用。
public class Outer {
private int num=10;
private class Inner {
public void show(){ System.out.println(num);
}
}
public void method(){ Inner i=new Inner(); i.show(); } }
public class demo
{ public static void main(String[] args) {
//Outer.Inner oi=new Outer().new Inner();
// oi.show();
Outer o=new Outer();
o.method(); } }
2.3 局部内部类(理解)
局部内部类定义位置
局部内部类是在方法中定义的类
局部内部类方式方式
局部内部类,外界是无法直接使用,需要在方法内部创建对象并使用
该类可以直接访问外部类的成员,也可以访问方法内的局部变量
public class Outer {
private int num=10;
public void method(){
//局部内部类是在方法中定义的类
int num2=20;
//局部内部类,外界是无法直接使用,需要在方法内部创建对象并使用
class Inner{
public void show(){
System.out.println(num);//10
System.out.println(num2);//20
}
}
Inner i=new Inner();
i.show();
}
}
public class OuterDemo {
public static void main(String[] args) {
Outer o=new Outer();
o.method();
}
}
public class Test {
public static void main(String[] args) {
//A.B d=new A().new B();
new A().new B().in();
System.out.println("===========");
new A().out();
System.out.println("==============");
System.out.println(new A.D().d);
System.out.println(new A.D().m);
//System.out.println(A.D.m);
}
}
class A{
String name="jack";
public void out(){
// B b=new B();
// b.in();
// System.out.println(b.age);
System.out.println("out.....");
// C c=new C();
// System.out.println(c.n);
// System.out.println("=========");
//
// D d=new D();
// System.out.println(d.m);
}
private class C{
double n=10;
}
static class D{
String d="tony";
static int m=200;
}
class B{
int age=20;
public void in(){
System.out.println(name);
System.out.println("in......");
}
}
}
2.4 匿名内部类(应用)
匿名内部类的前提
存在一个类或者接口,这里的类可以是具体类也可以是抽象类
匿名内部类的格式
格式:new 类名 ( ) { 重写方法 } new 接口名 ( ) { 重写方法 }
举例:
new Inter(){ @Override public void method(){} }
匿名内部类的本质
本质:是一个继承了该类或者实现了该接口的子类匿名对象
匿名内部类的细节
匿名内部类可以通过多态的形式接受
Inter i = new Inter(){ @Override public void method(){ } }
匿名内部类直接调用方法
public interface Jumpping {
void jump();
}
interface Inter{
void method();
}
class Test{
public static void main(String[] args){
new Inter(){
@Override
public void method(){
System.out.println("我是匿名内部类");
}
}.method(); // 直接调用方法
}
}
public class Test01 {
public static void main(String[] args) {
new Inter(){
@Override
public void method(){
System.out.println("匿名类");
}
}.method();
System.out.println("=========");
Inter a=new BB();
a.method();
System.out.println("========");
CC c=new CC(){
@Override
public void get() {
System.out.println("get");
}
@Override
public void del(int id) {
System.out.println(200);
}
};
c.del(200);
c.get();
}
}
interface Inter{
void method();
}
class BB implements Inter{
@Override
public void method(){
System.out.println(123);
}
}
interface CC{
void get();
void del(int id);
}
public class Test02 {
public static void main(String[] args) {
M m=new N();
m.test();
System.out.println("=========");
new N().test();
System.out.println("=======");
new M(){
@Override
public void test() {
System.out.println("545646");
}
}.test();
}
}
abstract class M{
public void show(){}
public abstract void test();
}
class N extends M{
@Override
public void test() {
System.out.println("test");
}
}
2.4 匿名内部类在开发中的使用(应用)
匿名内部类在开发中的使用
当发现某个方法需要,接口或抽象类的子类对象,我们就可以传递一个匿名内部类过去,来简化传统的代码
public class Cat implements Jumpping{
@Override
public void jump(){
System.out.println("猫可以跳高");
}
}
public class Dog implements Jumpping{
@Override
public void jump(){
System.out.println("狗可以跳高");
}
}
public class JumppingOperator {
public void method(Jumpping j){
j.jump();
}
}
public class Demo {
public static void main(String[] args){
//需求:创建接口操作类的对象,调用method方法
JumppingOperator jo=new JumppingOperator();
Jumpping j=new Cat();
jo.method(j);
System.out.println("=======");
Jumpping j1=new Dog();
jo.method(j1);
System.out.println("=======");
//匿名内部类的简化
jo.method(new Jumpping(){
@Override
public void jump(){
System.out.println("猫可以跳高");
}
});
System.out.println("=========");
//匿名内部类的简化
jo.method(new Jumpping(){
@Override
public void jump(){
System.out.println("狗可以跳高");
}
});
}
}
3. 常用API
3.1 Math(应用)
1、Math类概述
Math 包含执行基本数字运算的方法
2、Math中方法的调用方式
Math类中无构造方法,但内部的方法都是静态的,则可以通过 类名.进行调用
3、Math类的常用方法
public static int abs(int a): 返回参数的绝对值
public static double ceil(double a): 返回大于或等于参数的最小double值,等于一个整数
public static double floor(double a): 返回小于或等于参数的最大double值,等于一个整数
public static int round(float a): 按照四舍五入返回最接近参数的int
public static int max(int a,int b): 返回两个int值中的较大值
public static int min(int a,int b): 返回两个int值中的较小值
public static double pow (double a,double b): 返回a的b次幂的值
public static double random(): 返回值为double的正值,[0.0,1.0)
3.2 System(应用)
System类的常用方法
public static void exit(int status): 终止当前运行的 Java 虚拟机,非零表示异常终止
public static long currentTimeMillis(): 返回当前时间(以毫秒为单位)
public class SystemDemo {
public static void main(String[] args){
//在控制台输出1-10000,计算这段代码执行了多少毫秒
//获取开始时间节点
long start=System.currentTimeMillis();
for(int i=0;i<=10000;i++){
System.out.println(i);
}
//获取代码运行结束后的时间节点
long end=System.currentTimeMillis();
System.out.println("共耗时:"+(end-start)+"毫秒");
}
}
3.3 Object类的toString方法(应用)
Object类概述 "目的"
Object 是类层次结构的根,每个类都可以将 Object 作为超类。所有类都直接或者间接的继承自该类, 换句话说,该类所具备的方法,所有类都会有一份
查看方法源码的方式
选中方法,按下Ctrl + B
重写toString方法的方式
1. Alt + Insert 选择toString
2. 在类的空白区域,右键 -> Generate -> 选择toString
toString方法的作用:
以良好的格式,更方便的展示对象中的属性值
class Student extends Object{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString(){
return "Student {"+"name=' "+name+'\''+", age="+age+'}';
}
}
public class ObjectDemo {
public static void main(String[] args) {
Student s=new Student();
s.setName("秦岭下");
s.setAge(15);
System.out.println(s);//Student {name=' 秦岭下', age=15}
System.out.println(s.toString());//Student {name=' 秦岭下', age=15}
}
}
3.4 Object类的equals方法(应用)
equals方法的作用
用于对象之间的比较,返回true和false的结果
举例:s1.equals(s2); s1和s2是两个对象
重写equals方法的场景
不希望比较对象的地址值,想要结合对象属性进行比较的时候。
重写equals方法的方式
1. alt + insert 选择equals() and hashCode(),IntelliJ Default,一路next,finish即可
2. 在类的空白区域,右键 -> Generate -> 选择equals() and hashCode(),后面的同上。
class Student01{
private String name;
private int age;
public Student01() {
}
public Student01(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
//this--s1
//o--s2
if (this == o) return true;//比较地址是否相同,如果相同,直接返回true
//判断参数是否为null
//判断两个对象是否来自于同一个类
if (o == null || getClass() != o.getClass()) return false;
//向下转型
Student01 student01 = (Student01) o; //student s2
//比较年龄是否相同
if(age!=student01.age)return false;
//比较姓名内容是否相同
return name!=null?name.equals(student01.name):student01.name==null;
}
}
public class ObjectDemo01 {
public static void main(String[] args) {
Student01 S1=new Student01();
S1.setName("林青霞");
S1.setAge(13);
Student01 s2=new Student01();
s2.setName("林青霞");
s2.setAge(13);
//需求:比较两个对象的内容是否相同
System.out.println(S1.equals(s2));
}
}
3.5 冒泡排序原理(理解)
冒泡排序概述
一种排序的方式,对要进行排序的数据中相邻的数据进行两两比较,将较大的数据放在后面,依次对所有的数据进行操作,直至所有数据按要求完成排序
如果有n个数据进行排序,总共需要比较n-1次
每一次比较完毕,下一次的比较就会少一个数据参与
3.6 冒泡排序代码实现(理解)
public class ArrayDemo {
public static void main(String[] args) {
//定义一个数组
int[] arr={12,33,54,20,31,66};
System.out.println("输出排序前的数字:"+arrayToString(arr));
//第一次比较
for (int i = 0; i< arr.length-1; i++) {
if (arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
System.out.println("第一次比较后输出:"+arrayToString(arr));
//第二次比较
for (int i = 0; i< arr.length-1-1; i++) {
if (arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
System.out.println("第二次比较后输出:"+arrayToString(arr));
//第三次比较
for (int i = 0; i< arr.length-1-2; i++) {
if (arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
System.out.println("第三次比较后输出:"+arrayToString(arr));
//第四次比较
for (int i = 0; i< arr.length-1-0; i++) {
if (arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
System.out.println("第四次比较后输出:"+arrayToString(arr));
System.out.println("===================");
// 这里减1,是控制每轮比较的次数
for (int x = 0; x < arr.length-1; x++) {
// 1是为了避免索引越界,x是为了调高比较效率
for (int i = 0; i < arr.length-1-x; i++) {
if(arr[i]>arr[i+1]){
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
System.out.println("最后排序后:"+arrayToString(arr));
}
//把数组中的元素按照指定的规则组成一个字符串:[元素1, 元素2, ...]
public static String arrayToString(int[] arr){
//StringBuffer:字符串缓冲区
StringBuffer sb=new StringBuffer();
//append:附加
sb.append("[");
for(int i=0;i<arr.length;i++){
if(i==arr.length-1){
sb.append(arr[i]);
}else{
sb.append(arr[i]).append(",");
}
}
sb.append("]");
String s=sb.toString();
return s;
}
}
3.7 Arrays(应用)
Arrays的常用方法
public static String toString(int[] a): 返回指定数组的内容的字符串表示形式
public static void sort(int[] a): 按照数字顺序排列指定的数组
工具类设计思想
1、构造方法用 private 修饰
2、成员用 public static 修饰
public class ArraysDemo1 {
public static void main(String[] args) {
//定义一个数组
int[] arr={20,11,32,55,22,13};
System.out.println("排序前:"+ Arrays.toString(arr));
Arrays.sort(arr);
System.out.println("排序后:"+ Arrays.toString(arr));
}
}
二、.包装类
1.1 基本类型包装类(记忆)
基本类型包装类的作用
将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据
常用的操作之一:用于基本数据类型与字符串之间的转换
基本类型对应的包装类
基本数据类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
1.2 Integer类(应用)
Integer类概述
包装一个对象中的原始类型 int 的值
Integer类构造方法
public Integer(int value): 根据 int 值创建 Integer 对象(过时) //整型
public Integer(String s): 根据 String 值创建 Integer 对象(过时) //字符串
public static Integer valueOf(int i): 返回表示指定的 int 值的 Integer 实例
public static Integer valueOf(String s): 返回一个保存指定值的 Integer 对象 String
public class IntegerrDemo {
public static void main(String[] args) {
//Integer(int value):根据 int 值创建 Integer 对象(过时)
Integer i1=new Integer(100);
System.out.println(i1);//100
System.out.println("=============");
//Integer(String s):根据 String 值创建 Integer 对象(过时)
Integer i2=new Integer("100");
System.out.println(i2);//100
System.out.println("=============");
//Integer valueOf(int i):返回表示指定的 int 值的 Integer 实例
Integer i3=Integer.valueOf(100);
System.out.println(i3);//100
System.out.println("=============");
//Integer valueOf(String s):返回一个保存指定值的Integer对象String
Integer i4=Integer.valueOf("100");
System.out.println(i3);//100
System.out.println("=============");
}
}
BigDecimal:常用来解决精确的浮点数运算。
BigInteger:常用来解决超大的整数运算。
创建对象
BigDecimal.valueOf(2);
常用方法
add(BigDecimal bd): 做加法运算 substract(BigDecimal bd) : 做减法运算 multiply(BigDecimal bd) : 做乘法运算 divide(BigDecimal bd) : 做除法运算 divide(BigDecimal bd,保留位数,舍入方式):除不尽时使用 setScale(保留位数,舍入方式):同上 pow(int n):求数据的几次幂
public class Test04 {
public static void main(String[] args) {
System.out.println("请输入第一个数字");
double a=new Scanner(System.in).nextDouble();
System.out.println("请输入第二个数字");
double b=new Scanner(System.in).nextDouble();
//不精确
// System.out.println(a+b);
// System.out.println(a-b);
// System.out.println(a*b);
// System.out.println(a/b);
BigDecimal bd1 = BigDecimal.valueOf(a);
BigDecimal bd2 = BigDecimal.valueOf(b);
//加法运算
BigDecimal bd3;
bd3=bd1.add(bd2);
System.out.println(bd3.doubleValue());
//减法运算
bd3=bd1.subtract(bd2);
System.out.println(bd3.doubleValue());
//乘法运算
bd3=bd1.multiply(bd2);
System.out.println(bd3.doubleValue());
// bd3=bd1.divide(bd2);//报错除不尽
//保留位数和舍入方式
//除不尽时使用
bd3=bd1.divide(bd2,5,BigDecimal.ROUND_HALF_UP);
//保留两位
bd3=bd3.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bd3.doubleValue());
}
}
1.3 int和String类型的相互转换(记忆)
int转换为String
转换方式
方式一:直接在数字后加一个空字符串
方式二:通过String类静态方法valueOf()
public class IntegerDemo {
public static void main(String[] args) {
//int---String
int num=100;
String s1=num+" ";
System.out.println(s1);
System.out.println("=============");
String s2=String.valueOf(num);
System.out.println(s2);
}
}
String转换为int
转换方式
方式一:先将字符串数字转成Integer,再调用valueOf()方法
方式二:通过Integer静态方法parseInt()进行转换
public class IntegerDemo01 {
public static void main(String[] args) {
//String----int
String a="100";
//方式1:String --- Integer --- int
Integer i=Integer.valueOf(a);
//public int intValue()
int x=i.intValue();
System.out.println(x);
System.out.println("=========");
//方式2
//public static int parseInt(String s)
int y=Integer.parseInt(a);
System.out.println(y);
}
}
1.4 字符串数据排序案例(应用)
案例需求
有一个字符串:“91 27 46 38 50”,请写程序实现最终输出结果是:“27 38 46 50 91”
public class InterTest {
public static void main(String[] args) {
//定义一个字符串
String s = "91 27 46 38 50";
//把字符串中的数据存储到一个int类型的数组中;split: 分裂
String[] strArray = s.split(" ");
//定义一个int数组,把String[] 数组中的每一个元素存储到int数组中
int[] arr = new int[strArray.length];
for(int i=0; i<strArray.length; i++) {
System.out.print(strArray[i]+" ");
}
System.out.println();
System.out.println("==========");
//对int数组进行排序
Arrays.sort(arr);
//把排序后的int数组中的元素进行拼接得到一个字符串,这里拼接采用StringBuilder来实现
StringBuffer sb=new StringBuffer();
for(int i=0;i<arr.length;i++){
if(i==arr.length-1){
sb.append(arr[i]);
}else{
sb.append(arr[i]).append(" ");
}
}
String retult=sb.toString();
//输出结果
System.out.println(retult);
}
}
1.5 自动拆箱和自动装箱(理解)
自动装箱
把基本数据类型转换为对应的包装类类型
Integer i=Integer.valueOF(100); Integer ii=100;
自动拆箱
把包装类类型转换为对应的基本数据类型
//ii+=200; //ii=ii.intValue()+200; ii+=200;//自动完成装箱拆箱
Integer iii=null; if(iii!=null){ iii+=300;//NullPointerException }
Integer i = 100; // 自动装箱 i += 200; // i = i + 200; i + 200 自动拆箱;i = i + 200; 是自动装箱
注意:在使用包装类类型的时候,如果做操作,最好先判断是否为null
我们推荐的是 ,只要是对象,在使用前就必须进行不为null的判断
2.时间日期类
2.1 Date类(应用)
Date类概述
Date 代表了一个特定的时间,精确到毫秒
Date类构造方法
public Date(): 分配一个 Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒 public Date(long date): 分配一个 Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数
public class DateDemo01 {
public static void main(String[] args) {
//public Date():分配一个 Date对象,
// 并初始化,以便它代表它被分配的时间,精确到毫秒
Date d1=new Date();
System.out.println(d1);//Thu Apr 01 20:19:34 CST 2021
System.out.println("============");
//public Date(long date):分配一个 Date对象,
// 并将其初始化为表示从标准基准时间起指定的毫秒数
long date=1000*60*60;
Date d2=new Date(date);
System.out.println(d2);//Thu Jan 01 09:00:00 CST 1970
}
}
2.2 Date类常用方法(应用)
public long getTime(): 获取的是日期对象从1970年1月1日 00:00:00到现在的毫秒值
public void setTime(long time): 设置时间,给的是毫秒值
public class DateDemo02 {
public static void main(String[] args) {
//创建日期对象
Date d=new Date();
//long time=1000*60*60;
long time=System.currentTimeMillis();
d.setTime(time);
//System.out.println(d);//Thu Jan 01 09:00:00 CST 1970
System.out.println(d);//Thu Apr 01 20:20:15 CST 2021
}
}
2.3 SimpleDateFormat类(应用)
SimpleDateFormat类概述
SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。 我们重点学习日期格式化和解析
SimpleDateFormat类构造方法
public SimpleDateFormat(): 构造一个SimpleDateFormat,使用默认模式和日期格式
public SimpleDateFormat(String pattern): 构造一个SimpleDateFormat使用给定的模式和默认的日期格式
SimpleDateFormat类的常用方法
格式化(从Date到String)
public final String format(Date date):将日期格式化成日期/时间字符串
解析(从String到Date)
public Date parse(String source):从给定字符串的开始解析文本以生成日期
y 年
M 月
d 日
H 时
m 分
s 秒
public class SimpleDateFormatDemo {
public static void main(String[] args) throws ParseException {
//格式化:从 Date 到 String
Date d = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String s = sdf.format(d);
System.out.println(s);
System.out.println("--------");
//从 String 到 Date
String ss = "2048-08-09 11:11:11";
//ParseException
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(ss);
System.out.println(dd);
}
}
public class SimpleDateFormatDemo01 {
public static void main(String[] args)throws ParseException {
method();
}
public static void method() throws ParseException {
String date=new Scanner(System.in).nextLine();
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date birthday = sdf.parse(date);
birthday.getTime();
long start=birthday.getTime();
long now= System.currentTimeMillis();
System.out.println((now-start)/1000/60/60/24);
}
}
2.4 日期工具类案例(应用)
案例需求
定义一个日期工具类(DateUtils),包含两个方法:
(1)把日期转换为指定格式的字符串;
(2)把字符串解析为指定格式的日期,然后定义一个测试类(DateDemo),
测试日期工具类的方法
public class DateUtils {
private DateUtils(){}
/*
把日期转为指定格式的字符串
返回值类型:String
参数:Date date,String format
*/
public static String dateToString(Date date, String format){
SimpleDateFormat sdf=new SimpleDateFormat(format);
String s=sdf.format(date);
return s;
}
/*
把字符串解析为指定格式的日期
返回值类型:Date
参数:String s, String format
*/
public static Date StringToDate(String s,String format) throws ParseException {
SimpleDateFormat sdf=new SimpleDateFormat(format);
Date d=sdf.parse(s);
return d;
}
}
public class DateDemo {
public static void main(String[] args) throws ParseException {
//创建日期对象
Date d=new Date();
String s1=DateUtils.dateToString(d,"yyyy年MM月dd日 HH:mm:ss");
System.out.println(s1);//2021年04月01日 22:00:58
System.out.println("======================");
String s2=DateUtils.dateToString(d,"yyyy年MM月dd日");
System.out.println(s2);//2021年04月01日
System.out.println("======================");
String s3=DateUtils.dateToString(d,"HH:mm:ss");
System.out.println(s3);//22:00:58
System.out.println("======================");
String s="2048-08-09 12:12:12";
Date dd=DateUtils.StringToDate(s,"yyyy-MM-dd HH:mm:ss");
System.out.println(dd);//Sun Aug 09 12:12:12 CST 2048
}
}
2.5 Calendar类(应用)
Calendar类概述
Calendar 为特定瞬间与一组日历字段之间的转换提供了一些方法,并为操作日历字段提供了一些方法 Calendar 提供了一个类方法 getInstance 用于获取这种类型的一般有用的对象。
该方法返回一个Calendar 对象。
其日历字段已使用当前日期和时间初始化:Calendar rightNow = Calendar.getInstance();
Calendar类常用方法
public int get(int field): 返回给定日历字段的值
public abstract void add(int field, int amount): 根据日历的规则,将指定的时间量添加或减去给定的日历字段
public final void set(int year,int month,int date): 设置当前日历的年月日
public class CalendarDemo {
public static void main(String[] args) {
//获取日历类对象; Calendar:日历
Calendar c=Calendar.getInstance();
//public int get(int field):返回给定日历字段的值
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH)+1;
int date=c.get(Calendar.DATE);
System.out.println(year+"年"+month+"月"+date+"日");
System.out.println("===============");
/**public abstract void add(int field, int amount):
* 根据日历的规则,将指定的时间量添加或减去给定的日历字段
需求1:3年前的今天
*/
c.add(Calendar.YEAR,-3);
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH)+1;
date=c.get(Calendar.DATE);
System.out.println(year+"年"+month+"月"+date+"日");
System.out.println("===============");
//需求2:10年后的10天前
c.add(Calendar.YEAR,10);
c.add(Calendar.DATE,-10);
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH)+1;
date=c.get(Calendar.DATE);
System.out.println(year+"年"+month+"月"+date+"日");
System.out.println("===============");
//public final void set(int year,int month,int date):
// 设置当前日历的年月日
c.set(2050,10,10);
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH)+1;
date=c.get(Calendar.DATE);
System.out.println(year+"年"+month+"月"+date+"日");
}
}
2.6 二月天案例(应用)
案例需求 获取任意一年的二月有多少天
public class CalendarTest {
public static void main(String[] args) {
//键盘录入任意的年份
System.out.println("请输入年份:");
int year=new Scanner(System.in).nextInt();
//设置日历对象的年月日
Calendar c=Calendar.getInstance();
c.set(year, 2, 1);
//3月1日往前推一天,就是2月的最后一天
c.add(Calendar.DATE, -1);
//获取这一天输出即可
int date=c.get(Calendar.DATE);
System.out.println(year+"年的2月有"+date+"天");
}
}
3.异常
3.1 异常(记忆)
异常的概述
异常就是程序出现了不正常的情况
异常的体系结构(Throwable: 可投掷 )
Error : 严重问题,不需要处理
Exception : 称为异常类,它表示程序本身可以处理的问题
RuntimeException : 在编译期是不检查的,出现问题后,需要我们回来修改代码
非RuntimeException: 编译期就必须处理的,否则程序不能通过编译,就更不能正常运行了
Error 错误
Exception 例外
RuntimeException 运行时异常
3.2 JVM默认处理异常的方式(理解)
如果程序出现了问题,我们没有做任何处理,最终JVM会做默认的处理,处理方式有如下两个步骤: 把异常的名称,错误原因及异常出现的位置等信息输出在了控制台
程序停止执行
3.3 try-catch方式处理异常(应用)
定义格式
try { 可能出现异常的代码; } catch(异常类名 变量名) { 异常的处理代码; }
执行流程
程序从 try 里面的代码开始执行
出现异常,就会跳转到对应的 catch 里面去执行
执行完毕之后,程序还可以继续往下执行
public class ExceptionDemo01 {
public static void main(String[] args) {
System.out.println("开始");
method();
System.out.println("结束");
}
public static void method() {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
System.out.println("这里能够访问到吗");
} catch (ArrayIndexOutOfBoundsException e) {
// System.out.println("你访问的数组索引不存在,请回去修改为正确的索引");
e.printStackTrace();打印堆栈跟踪
}
}
}
ArrayIndexOutOfBoundsException: 数组索引超出范围异常
printStackTrace: 打印堆栈跟踪
3.4 Throwable成员方法(应用)
public String getMessage(): 返回此 throwable 的详细消息字符串
public String toString(): 返回此可抛出的简短描述
public void printStackTrace(): 把异常的错误信息输出在控制台
public class ExcepyionDemo01 {
public static void main(String[] args) {
System.out.println("开始");
method();
System.out.println("结束");
}
public static void method() {
try {
int[] arr = {1, 2, 3};
//new ArrayIndexOutOfBoundsException();
System.out.println(arr[3]);
System.out.println("这里能够访问到吗");
} catch (ArrayIndexOutOfBoundsException e) {
// System.out.println("你访问的数组索引不存在,请回去修改为正确的索引");
//e.printStackTrace();
//public String getMessage():返回此 throwable 的详细消息字符串
// System.out.println(e.getMessage());
//Index 3 out of bounds for length 3
//public String toString():返回此可抛出的简短描述
// System.out.println(e.toString());
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of boundsfor length 3
//public void printStackTrace():把异常的错误信息输出在控制台
e.printStackTrace();
// java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
// at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
}
}
}
3.5 编译时异常和运行时异常的区别(记忆)
编译时异常
都是Exception类及其子类
必须显示处理,否则程序就会发生错误,无法通过编译
运行时异常
都是RuntimeException类及其子类
无需显示处理,也可以和编译时异常一样处理
3.6 throws方式处理异常(应用)
定义格式
public void 方法() throws 异常类名 { }
public class ExceptionDemo02 {
public static void main(String[] args) {
System.out.println("开始");
//method();
try{
method2();
}catch (ParseException e){
e.printStackTrace();
}
System.out.println("结束");
}
//编译时异常
public static void method2() throws ParseException{
String s="2048-08-09";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=sdf.parse(s);
System.out.println(d);
}
//运行时异常
public static void method() throws ArrayIndexOutOfBoundsException{
int[] arr={1,2,3};
System.out.println(arr[3]);
}
}
注意事项
这个throws格式是跟在方法的括号后面的
编译时异常必须要进行处理,两种处理方案:try...catch …或者 throws,如果采用 throws 这种方案, 将来谁调用谁处理
运行时异常可以不处理,出现问题后,需要我们回来修改代码
3.7throws和throw的区别(记忆)
throws throw
用在方法声明后面,跟的是异常类名 用在方法体内,跟的是异常对象名
表示抛出异常,由该方法的调用者来处理 表示抛出异常,由方法体内的语句处理
表示出现异常的一种可能性,并不一定会发生这些异常 执行throw一定抛出了某种异常
3.8 自定义异常(应用)
自定义异常类
public class ScoreException extends Exception {
public ScoreException() {
}
public ScoreException(String message) {
super(message);
}
}
public class Teacher {
public void checkScore(int score) throws ScoreException{
if (score<0||score>100){
throw new ScoreException("你给的分数有误,分数应该在0-100之间");
}else{
System.out.println("成绩正常");
}
}
}
public class Demo {
public static void main(String[] args) {
System.out.println("请输入分数");
int score=new Scanner(System.in).nextInt();
Teacher t=new Teacher();
try{
t.checkScore(score);
}catch(ScoreException e){
e.printStackTrace();
}
}
}
三、集合(1)