第一天
一.内部类
1.关于局部内部类:它的书写位置,在外部类的成员方法中的定义的类。
特点:局部内部类可以访问外部类的成员变量包括私有。
如何访问局部内部类的的成员方法:在外部类的局部位置,访问内部类的成员方法,创建当前局部内部类对象来访问。
例子:
package innerclass_01;
//定义一个外部类
class Outer{
private int a =10;
private int b =20;
public void show(){
class Inter{ //定义一个内部类
public void method(){
System.out.println(a);//访问外部类的私有成员变量
System.out.println(b);
}
}
Inter inter = new Inter();//创建局部内部类的对象并访问自己的方法
inter.method();
}
}
//测试类
public class OuterDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.show();//由于内部类访问外部类的私有成员变量,故最后输出的是两个成员变量定义的值
}
}
输出结果:
10 20
2.局部内部类访问外部类局部变量的时候,应该注意哪些?
如何此时Java环境是Jdk7,局部内部类访问局部变量时,此时该变量必须显示加入final修饰。
原因:
局部变量的生命周期是随着方法调用而存在,随着方法调用结束而消失,而当前外部类对象调用
method 方法的时候,此时num进入栈内存,在局部位置创建了局部内部类对象,而局部内部类对
象调用它的成员方法访问该变量,方法method方法结束之后,内部类对象不会立即消失,它里面
的成员方法在访问局部变量,局部变量必须变成常量,常驻内存,否则如果当前变量消失了,局部
内部类的成员依然在访问,?此时就会出现冲突!所以 jdk7及jdk7以前版本的IDEA必须加入final修
饰,?jdk8通过jvm已经做了优化了,?无需手动加入final修饰.
例子:
package innerclass_01;
//外部类
class Outer2{
public void mothod (){ //成员方法
final int num = 10;//局部变量,此处要加final,但是现在都是jdk8版本以上了,
//所以加不加都可以了
class Inter2{
public void show(){
System.out.println(num);
}
}
Inter2 inter2 =new Inter2();
inter2.show();
}
}
public class OuterDemo2 {
public static void main(String[] args) {
Outer2 outer2 = new Outer2();
outer2.mothod();
}
}
输出结果:
10?
3.匿名内部类
匿名内部类:没有名字的内部类。
使用位置:一般在局部位置使用。
格式:?匿名内部类它是内部类的一种简化格式
?new 类名(可以是抽象类,也可以具体类)或者是接口名(){
? ? ? ?重写功能
? ? } ;
例子:
package innerclass_01;
//接口
interface Inter{
void show();//public abstract 可省略
void show1();
}
class Outer3{
public void method(){
//情况1.当接口里有有一种方法时
/*new Inter(){
@Override
public void show() {
System.out.println("情况一");
}
}.show();*/
//情况2.当接口里有有两种种方法时
/*new Inter(){
@Override
public void show() {
System.out.println("情况二");
}
@Override
public void show1() {
System.out.println("情况二");
}
}.show();
new Inter(){
@Override
public void show() {
System.out.println("情况二");
}
@Override
public void show1() {
System.out.println("情况二");
}
}.show1();*/
//优化:当接口有多种方法时,给匿名内部类起一个名字
Inter i = new Inter(){
@Override
public void show() {
System.out.println("优化后的方法");
}
@Override
public void show1() {
System.out.println("优化后的方法");
}
};
i.show();
i.show1();
}
}
public class OuterDemo3 {
public static void main(String[] args) {
Outer3 outer3 = new Outer3();
outer3.method();
}
}
输出结果(这里输出优化后的结果):
优化后的方法 优化后的方法
3.(1)方法的形参是一个接口,如何实现该方法:
/**
* @Date 2021/7/26
* 方法的形式参数如果是一个接口,实际需要传递的接口子实现类对象
*
* 方式1:将接口的子实现类定义出来
* 方式2;使用接口的匿名内部类
*/
//定义一个结婚的接口
interface Mary{
void mary() ;
}
//定义一个LoveDemo类
class LoveDemo{
public void funciton(Mary mary){//形式参数是一个接口
mary.mary();
}
}
//定义一个子类实现类
class You implements Mary{
@Override
public void mary() {
System.out.println("要结婚了,很开心...");
}
}
//测试类
public class LoveTest {
public static void main(String[] args) {
//方式1:需要调用LoveDemo类中的function方法
LoveDemo loveDemo = new LoveDemo() ; //或者使用匿名对象
//接口多态
Mary mary = new You() ;
loveDemo.funciton(mary);
System.out.println("----------------------------------------");
//方式2:接口的匿名内部类
//创建LoveDemo类对象
LoveDemo ld = new LoveDemo() ;
ld.funciton(new Mary() {
@Override
public void mary() {
System.out.println("要结婚了,很开心...");
}
});
}
}
二.使用JDK提供的API文档学习常用类中的常用功能
1.Object 功能类的 getClass() 方法
java.lang.Object:是类结构层次的根类(超类--->父类),所有的类都默认继承自Object子类(派生类)
Object功能类的getClass()方法
public final Class getClass():表示正在运行的类 (就是字节码文件对象)
Class----->反射的时候去使用
先去使用:
Class类:
功能:
public String getName():获取当前类的全限定名称(包名.类名)
面试题: ? ? ? ?获取一个类的字节码文件对象有几种方式? 三种 ? ? ? ? ? ?第一种:通过Object类的getClass()--->Class ? :正在运行的java类: class ?包名.类名 ? ? ? ? ? ? ? ? ? ? 第二种:任意Java类型的class属性----获取当前类的字节码文件对象Class ? ? ? ? ? ? ? ? ? ?第三种方式:Class里面forName("类的全限定名称(包名.类名)") ; (使用最多)
public class ObjectDemo {
public static void main(String[] args) throws ClassNotFoundException {
//创建一个学生类对象
Student s = new Student() ;
Class c1 = s.getClass();
System.out.println(c1);//class com.qf.generator_class_05.Student class 包.类名
Class c2 = s.getClass();
System.out.println(c2);//class com.qf.generator_class_05.Student class 包名.类名
System.out.println(c1 == c2);
//==在基本数据类型里面:比较的是数据值相同,在引用类型:比较的是两个对象的地址值是否相同
//Student.class---->就加载一次
System.out.println("---------------------------------");
Student s2 = new Student() ;
System.out.println(s == s2);//false :两个对象
System.out.println("----------------------------------");
//获取c1/c2 所代表的类 的全限定名称
// Class ---->class com.qf.generator_class_05.Student
String name1 = c1.getName();
String name2 = c2.getName();
System.out.println(name1);
System.out.println(name2);
System.out.println("--------------------------------");
//Class类中public static Class forName(String classname): 后期反射中使用
Class c3 = Class.forName("com.qf.generator_class_05.Student");
System.out.println(c1==c3);
System.out.println(c2==c3);
System.out.println("--------------------------------");
Class c4 = Student.class ; //任意Java类型的class属性----获取当前类的字节码文件对象Class
System.out.println(c4);
System.out.println(c1==c4);
System.out.println(c2==c4);
System.out.println(c3==c4);
}
}
//public class Student extends Object { //后面extends Object:任何类都默认继承自Object
public class Student {
public static void get(){
System.out.println("get student");
}
}
2.Object 的 public String toString() 方法
to String方法:返回对象的字符串表示形式;结果应该是一个简明扼要的表达,容易让人阅读,建议所有子类覆盖此方法。
描述一个对象:是由很多属性(成员变量组成),应该看到的具体的属性描述
? ? ? ? ? ? ? ? ? ? ? ? ??要么手动方式(不推荐)
? ? ? ? ? ? ? ? ? ? ? ? ? 也可以直接快捷键----重写toString即可
? ? ? ? ? ? ? ? ? ? ? ? ? 大部分的常用类或者后面的集合都会重写Object类的toString()
Object类的toString方法的原码
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Integer类:int类型的包装类类型
public static String toHexString(int i) :将整数转换成16进制数据--结果以String类型展示
3.
Object类的equals方法
public boolean equals(Object obj):判断当前obj对象是否和当前对象想等。
equals和==的区别:
==: ??连接的基本数据类型:比较的是数据值否相同
==: ? 连接的是引用类型,比较的是地址值是否相同
equals方法:如果使用Object默认的,底层还是使用==,默认比较的还是两个对象的地址值是否相同
Object类中的equals的源码
public boolean equals(Object obj) { //s1 ---this obj---->s2
return (this == obj); return s1 == s2 ; ==:引用类型:比较的是地址值是否相同
}
如何让让equals方法比较的是成员信息内容是否相同:重写Object的equals方法同时还需要重写hashCode;内容相同,还需要比较哈希码值相同;快捷键:alt+ins--->hashcode+equals方法。
重写之后,就比较的是成员信息的内容是否相同!
== 和equals ?? ?==:连接引用类型比较的是地址值 ?? ?equals:默认比较地址值,但是String类重写equals方法,所以内容是否相同
第二天
一.使用JDK提供的API文档学习常用类中的常用功能
1.克隆方法
protected Object clone() throws CloneNotSupportedException:创建对象并返回该对象的副本
这个方法会抛出一个异常,throws:表示的是可能出现异常,针对调用者必须进行处理。
要使用clone方法,当前某个对象所在的类必须实现"标记接口"Cloneable(没有字段(成员变量),也没有成员方法);实现这个接口,那么就可以使用Object的clone()方法。
2.java.lang.String:代表的字符串
String ?变量名 = "abc" ;????????//abc代表 的当前String的实例
?String类常用的功能: ?? ? ? ? ?获取功能: ?? ? ? ? ? ? ? ? int length():获取字符串长度 ? ??面试题: ?? ? ? ? ? ?在数组中有没有length方法,在String类中有没有length方法,在集合中有没有length方法
?? ? ? ? ? ? ?数组中就没有 length 方法, length 是属性 ?? ? ? ? ? ? ?int[] arr = new int[3] ; ? ? ? ? ? ? ? arr.length;
?? ? ? ? ? ? ?String类中有length()方法 ?? ? ? ? ? ? ?集合中没有 length() 方法 ,----->而是 size() 方法,用来获取元素数
构造方法:
public String():空参构造:空字符序列
public String(byte[] bytes):将一个字节数组构造成一个字符串,使用平台默认的字符集(utf-8:一个
中文对应三个字节) 解码
编码和解码---保证字符集统一
编码:将一个能看懂的字符串---->字节 "今天老地方见" utf-8
解码:将看不懂的字节---->字符串 "今天老地方见" gbk
public String(byte[] bytes,字符集):使用指定的字符集,将字节数组构造成一个字符串
public String(byte[] bytes,int offset,int length):将指定的部分字节数组转换成字符串
参数1:字节数组对象,参数2:指定的角标值 参数3:指定长度
public String(char[] value):将字符数组构造成一字符串
public String(char[] value,int offset,int count):将部分字符数组转换成字符串
public String(String original):构造一个字符串,参数为字符串常量
字符串的特点:字符串是一个常量,一旦被赋值了,其值(地址值)不能被更改。
String s1 = "hello" ;
创建了一个对象,直接在常量池创建,开辟常量池空间
String s2 = new String("hello") ;
创建了两个对象,一个堆内存中开辟空间,一个指向常量池(不推荐)
直接赋值的形式
?字符串变量相加,常量池中先开空间,在拼接
字符串常量相加,先相加,然后看结果是否在常量池中存在;
如果存在,直接返回当前地址值,如果不存在,在常量池开辟空间!
public class StringTest {
public static void main(String[] args) {
String s1 = "hello" ;
String s2 = "world" ;
String s3 = "helloworld" ;
System.out.println(s3 == (s1+s2)); //s1+s2:先开空间,在拼接 false
System.out.println(s3.equals(s1+s2)); //true
System.out.println("----------------------");
System.out.println(s3 == "hello"+"world"); //先拼接,然后再常量池中找,存在,直接返回地址
System.out.println(s3 .equals("hello"+"world"));
}
}
3.String类的常用的转换功能: (重点)
byte[] getBytes() :将字符串转换成字节数组 (编码)
如果方法为空参,使用平台默认的编码集进行编码(utf-8:一个中文对应三个字节)
byte[] getBytes(String charset):使用指定的字符集进行编码
解码的过程:将看不懂的字节数----->String
String(byte[] bytes):使用默认字符集进行解码
String(byte[] bytes,指定字符集)
编码和解码必须要保证字符集统一
字符集:
gbk :一个中文两个字节(中国中文编码表)
gb2312:gbk升级版(含义有一个中文字符:中国的中文编码表)
iso-8859-1:拉丁文码表
utf-8:任何的浏览器--->都支持 utf-8格式 (后期统一个)
unicode:国际编码表
JS:日本国际 电脑系统 一个字符集
Arrays类
静态功能:
public static String toString(int/byte/float/double...[] a):将任意类型的数组-->String
public char[] toCharArray():将字符串转换成字符数组
public String toString():返回自己本身---"当前字符串的内容"
public String toUpperCase():将字符串转换成大写
public String toLowerCase():将字符串转换成小写
实例:
public class StringDemo {
public static void main(String[] args) throws UnsupportedEncodingExcept ion {
//定义一个字符串
String str = "中国" ;
byte[] bytes = str.getBytes();//默认utf-8
// byte[] bytes = str.getBytes("gbk");//指定字符集
// public static String toString(byte[] a)
System.out.println(Arrays.toString(bytes));//[-28, -72, -83, -27, -101, -67]
//[-42, -48, -71, -6]
System.out.println("------------------------------");
//解码
// String strResult = new String(bytes,"gbk") ;//gbk:一个中文对应两个字节 //使用平台默认解码集进行解码: utf-8
String strResult = new String(bytes) ;// //使用平台默认解码集进行解码: utf-8
System.out.println(strResult);
System.out.println("--------------------------------------");
//定义一个字符串
String s2 = "helloworldJavaEE" ;
// public char[] toCharArray()
char[] chs = s2.toCharArray();
//遍历字符数组
for(int x = 0 ; x < chs.length; x ++){
System.out.println(chs[x]);
}
System.out.println("-----------------------");
System.out.println(s2.toString());
System.out.println("-----------------------");
//转换大小写
System.out.println(s2.toUpperCase());
System.out.println(s2.toLowerCase());
}
}
4.String类型的判断功能
public boolean equals(Object anObject):比较两个字符的内容是否相同 (区分大小写)
public boolean equalsIgnoreCase(String anotherString):比较两个字符串是否相同(不区分大小写)
public boolean startsWith(String prefix):判断字符串是否以指定的内容开头
public boolean endsWith(String suffix):判断字符串是否以指定的内容结尾
需求:在某个时间点(今天下午18:00 将某个目录下的所有的以.java文件结尾删除)
Java中定时器类:Timer---->定时任务TimerTask(抽象类)
表示文件或者文件夹的抽象路径形式:File类
递归删除 (定义方法删除)
boolean isEmpty() 判断字符串是否为空 :若为空,则返回true;否则返回false
String s = "" ;// 空字符串 ,存在String对象 ""
String s = null ; 空值 (空对象) null:引用类型的默认值
实例:
public class StringDemo2 {
public static void main(String[] args) {
String s1 = "helloJavaEE" ;
String s2 = "hellojavaee" ;
// public boolean equals(Object anObject):比较两个字符的内容是否相同 (区分大小写)
System.out.println("equals:"+s1.equals(s2));
// public boolean equalsIgnoreCase(String anotherString)
System.out.println("equalsIgnoreCase():"+s1.equalsIgnoreCase(s2));
/**
* public boolean startsWith(String prefix):判断字符串是否以指定的内容开头
* public boolean endsWith(String suffix):判断字符串是否以指定的内容结尾
* boolean isEmpty() 判断字符串是否为空 :若为空,则返回true;否则返回false
*/
System.out.println("startsWith():"+s1.startsWith("hel"));
System.out.println("startsWith():"+s1.startsWith("ak47"));
System.out.println("endsWith():"+s1.endsWith("EE"));
s1 = "" ; //length()---->长度0 (空字符序列)
System.out.println(s1.isEmpty());
}
}
练习题:
/**
* @Date 2021/7/27
* 需求:
* 已知一个用户名和密码,然后键盘录入用户名和密码,给三次机会,
* 如果用户名和密码一直,提示 "登录成功",----->开启 猜数字游戏(定义类:StartGame 里面
* 静态功能:start())
* 如果机会用完了, 换一种 提示"账号被锁定,请联系管理员"
* 如果没有用完,提示"您还剩xxx"次机会...
*
* 分析:
* 1)给定用户名和密码
* username admin
* password amdin
* 2)三次机会-----明确循环次数:for--- x =0,1,2
* 创建键盘录入对象
* 录入用户名name
* 录用用户名pwd
*
* 判断如果name和 username 并且 pwd和password一致,登录成功
*
*
* 换一种提示:可能不一致
* 判断如果当前 2-x == 0,用完了 "账号被锁定,请联系管理员"
* 否则,您还剩2-x"次机会
*
*
* debug模式调试程序:当程序出现问题,可以使用debug来查看变量的变化
* f8:下一步
* f7:跳入到某个jdk提供的api的方法中
* 举例:某行代码 nextLine() ; 进入到源码
*
* shift+f8:从原码中回到上一个断点处
*
*/
public class StringTest {
public static void main(String[] args) {
// 1)给定用户名和密码
String username = "admin" ;
String password = "admin" ;
//2)循环3次机会
for(int x = 0 ; x < 3 ;x ++){
//创建键盘录入对象
Scanner sc = new Scanner(System.in) ;
//提示并录入数据
System.out.println("请您输入用户名:");
String name = sc.nextLine() ;
System.out.println("请您输入密码:");
String pwd =sc.nextLine() ;
if(username.equals(name) && password.equals(pwd)){
System.out.println("登录成功,准备开始玩游戏...");
StartGame.start();
break ; //结束
}
//当机会用完了
if((2-x)==0){
System.out.println("对不起,您的账号被锁定,请联系管理员");
}else{
System.out.println("您还剩下"+(2-x)+"次机会");
}
}
}
}
5.String类的获取功能:(重点)
/**
* @Date 2021/7/27
* String类的获取功能:(重点)
*
* int length():获取字符串长度
* public char charAt(int index);获取指定索引处的字符
* public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串
* public int indexOf(int ch):返回指定字符第一次出现的索引值
* public int lastIndexOf(int ch):返回值指定字符最后一次出现的索引值
* public String[] split(String regex):
* 拆分功能:通过指定的格式将字符串---拆分字符串数组
* public String substring(int beginIndex) :从指定位置开始默认截取到末尾
* 角标从0开始
* public String substring(int beginIndex,int endIndex)
* 从指定位置开始,截取到位置结束(包前不包右)
* 只能取到endIndex-1处
*
* public static String valueOf(boolean/int/long/float/double/char...Object b)
* 万能方法,将任意类型转换String类型
*/
public class StringDemo {
public static void main(String[] args) {
String str = "helloworldJavaEE" ;
// public char charAt(int index);获取指定索引处的字符
System.out.println("charAt():"+str.charAt(4));
System.out.println("---------------------------------");
//public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串
//字符串最传统的拼接:直接 定义一个String s = "" ; s+任何数据="xxx" ;
//提供了一个功能
System.out.println("concat:"+str.concat("R").concat("Go"));
System.out.println("-----------------------------------");
// public int indexOf(int ch):返回指定字符第一次出现的索引值
// public int lastIndexOf(int ch):返回值指定字符最后一次出现的索引值
System.out.println("indexOf():"+str.indexOf("o"));
System.out.println("lastIndexOf():"+str.lastIndexOf("o"));
System.out.println("-----------------------------------");
//public String[] split(String regex):
String str2 = "JavaEE-Python-Go-R-C-C#-PHP" ;
//使用"-"进行拆分
String[] strArray = str2.split("-");
for(int x = 0 ; x < strArray.length ; x ++){
System.out.print(strArray[x]+"\t");
}
System.out.println();
System.out.println("-----------------------------------");
/**
* public String substring(int beginIndex) :从指定位置开始默认截取到末尾
* 角标从0开始
* public String substring(int beginIndex,int endIndex)
*/
// String str = "helloworldJavaEE" ;
System.out.println("subString():"+str.substring(5));
System.out.println("subString():"+str.substring(5,9));//worl
System.out.println("-----------------------------------");
//public static String valueOf(基本类型以及Object)
System.out.println("valueOf:"+String.valueOf(100)); //100--->"100"
}
}
6.String类的按照字典顺序比较以及源码分析
E:\day16\avi
7.?StringBuffer
StringBuffer:字符串缓冲区 ---->类似于String,但是不一样 (可变的字符序列)。
线程安全---->同步的----->执行效率低
StringBuilder:和StringBuffer具有相互兼容的API,它是线程不安全的类---->不同步----->执行效率高
获取功能:public int length():获取字符数(长度);
? ? ? ? ? ? ? ? ??public int capacity():获取字符串缓冲区容量
第三天
一String的练习题
1.String类的遍历:将字符串的每一个字符分别输出。
可以使用String类的获取功能:charAt(int index) ---->char
public class StringTest {
public static void main(String[] args) {
String str = "helloJavaEE";//创建一个字符串
System.out.println(str.charAt(0));//原始的做法、
System.out.println(str.charAt(1));
System.out.println(str.charAt(2));
System.out.println(str.charAt(3));
System.out.println(str.charAt(4));
System.out.println(str.charAt(5));
System.out.println(str.charAt(6));
System.out.println(str.charAt(7));
System.out.println(str.charAt(8));
System.out.println(str.charAt(9));
System.out.println(str.charAt(10));
System.out.println("---------------------------------");
//循环改进: 利用String类的length()方法:获取字符串长度 + charAt(int index)
for(int x = 0;x<str.length();x++){
System.out.println(str.charAt(x));
}
System.out.println("--------------------------");
//使用String类的转换功能
//String---->字符数组toCharArray()--->char[]
char[] chs = str.toCharArray();
for(int x = 0 ; x < chs.length ; x ++){
char ch = chs[x] ;
System.out.println(ch);
}
}
}
2.已知一个数组,静态初始化,将数组拼接成String类型。
定义一个将数组转换成String的功能,返回值就是String。
拼接符号????????+
concat()? ? ? ? ?拼接功能
举例:
package string_test_01;
public class StringTest2 {
public static void main(String[] args) {
int[]arr={1,2,3,4,5,6};//创建静态初始化数组
String string = array2String(arr);//最后把数组arr带入array2String方法,因为arr是实
System.out.println(string); // 参,所以Sstring str 接受出来的结果,然后输出str就可以
}
public static String array2String(int []arr){
//定义一个空字符串
String result = "";
//拼接左中括号
result+="[";
//遍历数组,获取每一个元素
for(int x =0; x<arr.length;x ++){
//判断是否是最大角标
if(x==arr.length-1){
result += arr[x];
result +="]";
}else {
//拼接逗号和空格
result += arr[x];
result += ", ";
}
}
return result;
}
}
//输出结果:
[1, 2, 3, 4, 5, 6]
3.键盘录入字符串,将字符串进行反转(使用功能改进) ?String转换功能
package string_test_01;
import java.util.Scanner;
/**
* 键盘录入字符串,将字符串进行反转(使用功能改进) String转换功能
*
* 方式2 :StringBuffer:里面有反转功能
*/
public class StringTest3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);//创建键盘录入对象
System.out.println("请您输入一个字符串");//提示并录入数据
String str = sc.nextLine();
//调用功能
String result = reveres(str);
System.out.println(result);
}
/**
* 定义字符串反转功能
* @param s 将指定的字符串进行反转
* @return 返回需要的反转的字符串值
*/
private static String reveres(String s) {
//定义一个结果变量
String rersult = "";
//将字符串转换成char[]
char[] chs = s.toCharArray();//转换功能
for(int x = chs.length-1 ; x>=0 ; x --){
rersult +=chs[x];
}
return rersult;
}
}
//输出结果:
请您输入一个字符串
hello
olleh
二StringBuffer
1.添加功能:StringBuffer ?append
/**
* @Date 2021/7/28
*
* StringBuffer: 线程安全的类 (执行效率低) :字符串缓冲区:里面存储的字符序列
*
* 添加功能:
* StringBuffer append(任何类型) :将内容追加到字符串缓冲区中 (在字符串缓冲区的最后一个字符序列的末尾追加)
* 返回值是字符串缓冲区本身...
*
* public StringBuffer insert(int offset,String str):插入:在指定位置处插入指定的内容
*
*/
public class StringBufferDemo {
public static void main(String[] args) {
//创建一个字符串缓冲区对象
StringBuffer sb = new StringBuffer() ;
System.out.println("sb:"+sb);
//StringBuffer append(任何类型) 可以添加任何类型,在最后面添加
sb.append("hello").append("world").append(100).append('a').append(12.34).append(new Object()) ;
System.out.println("sb:"+sb);
System.out.println("----------------------------------");
//public StringBuffer insert(int offset,String str)
//在指定位置前面插入指定的内容,指定位置是从第一个开始数
sb.insert(5,"高圆圆") ;
System.out.println("sb:"+sb);
}
}
2.StringBuffer的删除功能
/**
* @Date 2021/7/28
* StringBuffer的删除功能
* public StringBuffer deleteCharAt(int index):删除指定索引处的缓冲区的字符序列,返回字符串缓冲区本身
* public StringBuffer delete(int start,int end):删除从指定位置到指定位置结束的字符序列(包含end-1处的字符),返回字符串缓冲区本身
* [start,end-1]
*/
public class StringBufferDemo2 {
public static void main(String[] args) {
//创建一个StringBuffer对象 (默认初始容量16)
StringBuffer buffer = new StringBuffer() ;
buffer.append("hello").append("world").append("Javaee") ;
System.out.println(buffer);
System.out.println("---------------------------");
//public StringBuffer deleteCharAt(int index)
//删除e这个字符
// System.out.println("deletCharAt():"+buffer.deleteCharAt(1));
//删除第一个l字符
// System.out.println("deletCharAt():"+buffer.deleteCharAt(1));
//public StringBuffer delete(int start,int end):
//删除world这个子字符串
System.out.println("delete():"+buffer.delete(5,10));//5-9
}
}
3.StringBuffer类型的相互转换(重点)
/**
* @Date 2021/7/28
*
* 类型的相互转换(重点)
*
* 开发中:
* 本身A类型,由于需要使用B类型的功能,所以 A类型---->B类型
*
* A类型,需要使用B类型的功能,A--->B类型,使用完功能之后,又可能结果又需要A类型,
* B类型---->A类型
*
*
* String---->StringBuffer
* StringBuffer---->String
*/
public class StringBufferDemo3 {
public static void main(String[] args) {
//String---->StringBuffer
String s = "hello" ;
//错误的写法
// StringBuffer sb = s ;//两个类型不一致
//方式1:StringBuffer有参构造方法
StringBuffer sb = new StringBuffer(s) ;
System.out.println(sb);
System.out.println("---------------------------");
//方式2:StringBuffer的无参构造方法 结合append(String str)
StringBuffer sb2 = new StringBuffer() ;
sb2.append(s) ;//追加功能
System.out.println(sb2);
System.out.println("-------------------------------------------");
//StringBuffer---->String
//创建字符串缓冲区对象
StringBuffer buffer = new StringBuffer("helloJavaee") ;
//方式1:String类型的构造方法
//public String(StringBuffer buffer)
String str = new String(buffer) ;
System.out.println(str);
System.out.println("-------------------------------------------");
//方式2:StringBuffer的public String toString()方法
String str2 = buffer.toString();
System.out.println(str2);
}
}
4.StringBuffer的特有功能
import java.util.Scanner;
/**
* @Date 2021/7/28
* StringBuffer的特有功能
* public StringBuffer reverse(),反转之后,返回的是字符串缓冲区本身
*
* 键盘录入一个字符串,将字符串进行反转--->使用功能改进
*/
public class StringBufferDemo4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
//提示并录入
System.out.println("请您输入一个字符串:");
String line = sc.nextLine() ;
//需要用StringBuffer的特有功能 reverse
//line---->StringBuffer类型
StringBuffer sb = new StringBuffer(line) ;
String result = sb.reverse().toString();
System.out.println(result);
System.out.println("-----------------------------");
//调用功能
String result2 = reverse(line);
System.out.println(result2);
}
/**
* reverse反转功能
* @param s 将指定的字符串反转
* @return 返回结果字符串
*/
public static String reverse(String s){
//分步走
//方式1:s---->StringBuffer类型---->有参构造
//StringBuffer buffer = new StringBuffer(s) ;
//return buffer.reverse().toString() ;
//方式2:append()+空参构造方法
/*StringBuffer buffer = new StringBuffer() ;
String result = buffer.append(s).reverse().toString();
return result ;*/
//匿名对象
return new StringBuffer().append(s).reverse().toString() ;
}
}
5.StringBuffer的截取功能
/**
* @Date 2021/7/28
*
* StringBuffer的截取功能
* public String substring(int start):从指定位置开始,默认截取到末尾,返回值是新的字符串
* public String substring(int start,int end):从指定位置开始到指定end-1结束进行截取,返回的新的字符串
*
*
* StringBuffer的替换功能
* public StringBuffer replace(int start, 起始索引
* int end, 结束索引(end-1)
* String str) 替换的内容
*/
public class StringBufferDemo5 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer() ;
sb.append("hello").append("world").append("javaee").append("anroid") ;
System.out.println("sb:"+sb);
// System.out.println(sb.substring(5));//subString(xx)---->截取的新的字符串
//System.out.println("sb:"+sb);
// System.out.println(sb.substring(5,10));//end-1位置
System.out.println("------------------------------------");
//public StringBuffer replace(int start, 起始索引
// int end, 结束索引(end-1)
// String str) 替换的内容
System.out.println(sb.replace(5,10,"高圆圆"));
}
}
6.StringBuffer的特点和应用等问题
import java.util.Arrays;
/**
* @Date 2021/7/28
*
* 面试题:
* StringBuffer和数组的区别?
*
* 数组:只能存储同一种数据类型容器
* 数组可以存储基本类型,也可以存储引用类型
*
* 数组的最大特点:长度固定
* 静态初始化int[] arr = {元素1,元素2,元素3...} ;/动态初始化 int[] arr = new int[长度];
* String[] strArray = {"xx","xx","xx"} ;
*
* StringBuffer:支持可变的字符序列
* 里面存储可以存储任意类型的元素
* append(int/char/double/float/Obejct/String)
* isnert(int offert,int/char/double/float/Obejct/String)
*
* 一般情况:开发中 将StringBuffer----->String
*
*
* 面试题:
* 集合/数组的区别?(等会说)
*
*
*
* 面试题:
* StringBuffer,StringBuilder和String的区别?
* String:字符串是一个常量,一旦被赋值,其值不能更改/作为形式参数属于特殊的引用类型,形式参数的改变不会实际参数
*
* StringBuffer:可变的字符序列,线程安全的类----同步的----->执行效率低(线程角度)
* StringBuilder:可变的字符序列.和StringBuffer具有相互兼容的api,单线程程序中(只考虑执行效率,不考虑安全问题),
* 会使用StringBuilder替代StringBuffer
*
* 作为方法的形式参数,形参的改变会直接实际参数
*
* 应用场景:
* Arrays.toString()--->源码 ---->StringBuilder "[]"
* 网络聊天室
* 集合+多线程+io流
* 私聊
* 公聊
* 在线列表
* ...
* JavaSE
* 好友的在线列表
* 高圆圆--->查询当前在线列表
* 可以StringBuilder/StringBuffer进行追加...
* 1,张三
* 2,李四
* 3,王五
*/
public class StringBufferTest {
public static void main(String[] args) {
//int[] arr = {11,22,33,44,55} ;//int[] arr = new int[]{11,22,33,44,55}
//System.out.println(Arrays.toString(arr));
String s = "hello" ;
System.out.println("s:"+s);
change(s) ;
System.out.println("s:"+s);
System.out.println("-------------------------");
StringBuffer sb = new StringBuffer("android") ;
System.out.println("sb:"+sb);
change(sb) ;
System.out.println("sb:"+sb);//androidjavaee
}
public static void change(StringBuffer sb){//StringBuffer作为形参
sb.append("javaee") ;//缓存区中追加了javaee
System.out.println("sb:"+sb);
}
public static void change(String s) {//String作为形参:和基本数据类型一致(String是一个常量)
s = s +"worldjavaee" ;
System.out.println("s:"+s);
}
}
三.Integer的 引入
1.Integer的构造方法:将int类型和String类型(此时的String中的值必须为数字字符串"9")包装为Integer类型
package integer_03;
/**
* @Author Kuke
* @Date 2021/7/28
* Integer的构造方法:
* Integer(int value):可以将int类型包装为Integer类型
* Integer(String s) throws NumberForamtException: 抛出一个数字格式化异常
* 注意事项:
* 当前字符串如果不是能够解析的整数的,就会出现数字格式化异常,str必须为 数字字符串
*/
public class IntegerDemo2 {
public static void main(String[] args) {
int i =100;
Integer in =new Integer(i);
System.out.println(in);
System.out.println("----------------");
//String str="hello";//不能为字符串,
String str2= "9"; //必须为数字字符串
Integer in2=new Integer(str2);
System.out.println(in2);
}
}
输出结果;
100
----------------
9
2.自动拆装箱:int---->Integer?装箱;Integer---->int?拆箱。
package integer_03;
/**
* @Date 2021/7/28
*
* JDK5以后新特性:
* 自动拆装箱,可变参数,静态导入,增强for循环,<泛型>,枚举类
*
*
* 自动拆装箱:
* 基本类型---> 对应的包装类类型 (装箱)
* int---->Integer
*
* 对应的包装类型---->基本类型 (拆箱)
* Integer---->int
*
*/
public class IntegerDemo3 {
public static void main(String[] args) {
int i =100;
Integer ii =new Integer(i);
ii +=200; //先拆箱--Integer--->int + 200;然后再nt---->Integer 装箱
System.out.println("ii:"+ii);
/**
*通过反编译工具查看
int i = 100;
Integer ii = new Integer(i); //创建Integer类对象
ii = Integer.valueOf(ii.intValue() + 200); ii = Integer.valueIf(先拆箱--Integer--->int + 200)
//将300赋值Integer变量ii,底层使用valueOf(int)--->int---->Integer 装箱
System.out.println((new StringBuilder()).append("ii:").append(ii).toString());//以字符串形式输出出来
*/
}
}
输出结果:
ii:300
3.int和String类型的相互转换
package integer_03;
/**
* @Date 2021/7/28
*
* 将int---->String
* Integer作为桥梁
* String---->int
*/
public class IntegerDemo4 {
public static void main(String[] args) {
//int--->String
int i =50;
/* //定义一个空串然后拼接i
String result="";//定义一个空串
result =result+i;
System.out.println(result);//数字字符串"50"*/
//使用功能
//方式1: Integer类的静态功能(推荐)
//public static String toString(int i)
String str = Integer.toString(i); //Integer.toString(i);然后Alt+回车键生产
System.out.println(str);
System.out.println("--------------------------------");
//方式2:int---->Integer---->public String toString()
Integer ii =new Integer(i);
String str2 = ii.toString();//底层使用的方法public static String toString(int i)
System.out.println(str2);
System.out.println("-------------------------------------------------");
//String----->int;(使用居多)
//开发中:浏览器(客户端)---->传递给后端的数据(String类型)
//方式1:public static int parseInt(String s)throws NumberFormatException:数字字符串 (使用最多)
//通用方法:String--->long Long.parseLong(String s)---->long
// String ----double Double public static double parseDouble(String s)
String s= "60";
int i1 = Integer.parseInt(s);//Integer.parseInt(s);然后Alt+回车键生产
System.out.println(i1);
System.out.println("-------------------");
//方法2
//Strimg -----> Integer ----->int
//Integer的构造方法 Integer(String s)
//Integer 的成员方法:int intValue()--->int
Integer ii2 =new Integer(s) ;
int i2 = ii2.intValue();//ii2.intValue();然后Alt+回车键生产
System.out.println(i2);
}
}
输出结果:
50
--------------------------------
50
-------------------------------------------------
60
-------------------
60
四.Character类
1.通过统计大写字母字符和数字字符引入Character类
package character_04;
import java.util.Scanner;
/**
* @Date 2021/7/28
* 需求:
* 键盘录入一个字符串,有大写字母字符,数字字母字符,小写字母字符,不考虑其他字符,分别统计
* 大写字母字符,小写字母字符,数字字符的个数!
*
* 输入:
* "Hello123World"
*
* 输出:
* 大写字母有2个
* 小写字母字符:8个
* 数字字符:3个
*
* 分析:
* 0)定义三个统计变量
* bigCount
* smallCount
* numberCount
* 1)键盘录入一个字符串
* 2)
* 方式1 获取到每一个字符, 字符对应ASCII码表的值 (太麻烦)
* 方式2:将字符串转换成字符数组
* 3)遍历字符数组
* 获取到每一个字符
* 如果当前字符 'A', 'Z' 大写字母字符 bigCount ++
* 'a' ,'z' 小写字母字符 smallCount++
* '0','9' 数字字符 numberCount++
*
*/
public class Test {
public static void main(String[] args) {
//定义三个统计变量
int bigCount = 0 ;
int smallCount = 0 ;
int numberCount = 0;
//创建键盘录入对象
Scanner sc = new Scanner(System.in) ;
//提示并录入数据
System.out.println("请您输入一个数据:");
String line = sc.nextLine() ;
//转换成字符数组
char[] chs = line.toCharArray();
for (int i = 0; i <chs.length ; i++) {
char ch = chs[i] ;
/* //判断
if(ch>='A' && ch<='Z'){
//大写字母
bigCount ++ ;
}else if(ch>='a' && ch<='z'){
//小写字母
smallCount ++ ;
}else if(ch >='0' && ch<='9'){
numberCount ++ ;
}*/
//直接判断
if(Character.isDigit(ch)){
numberCount ++ ;
}else if(Character.isUpperCase(ch)){
bigCount ++ ;
}else if(Character.isLowerCase(ch)){
smallCount ++;
}
}
System.out.println("大写字母字符有"+bigCount+"个");
System.out.println("小写字母字符有"+smallCount+"个");
System.out.println("数字字符有"+numberCount+"个");
}
}
输出结果:
请您输入一个数据:
HELLOWorldJavaEE202106
大写字母字符有9个
小写字母字符有7个
数字字符有6个
2.Character的判断功能
package character_04;
/**
* @Date 2021/7/28
*
* Charcater :char类型的包装类类型,
*
* 构造方法
* *public Character(char value)
*
* 主要了一些功能
* public static boolean isUpperCase(char ch):判断当前字符是否大写字母字符
* public static boolean isLowerCAse(char ch):是否为小写字母字符
* public static boolean isDigit(char ch):是否为数字字符
*
*
* //String转换的功能很类似
* public static char toLowerCase(char ch):将字符转换成小写
* public static char toUpperCase(char ch):将字符转换成大写
*/
public class CharacterDemo {
public static void main(String[] args) {
//创建字符类对象
Character character = new Character('a') ;
// Character character = new Character((char)(97)) ;
System.out.println(character);
System.out.println("---------------------------------");
System.out.println("isUpperCase():"+Character.isUpperCase('A'));
System.out.println("isUpperCase():"+Character.isUpperCase('a'));
System.out.println("isUpperCase():"+Character.isUpperCase('0'));
System.out.println("---------------------------------");
System.out.println("isLowerCase():"+Character.isLowerCase('A'));
System.out.println("isLowerCase():"+Character.isLowerCase('a'));
System.out.println("isLowerCase():"+Character.isLowerCase('0'));
System.out.println("---------------------------------");
System.out.println("isDigit():"+Character.isDigit('A'));
System.out.println("isDigit():"+Character.isDigit('a'));
System.out.println("isDigit():"+Character.isDigit('0'));
// char ch = 'a' ;
// System.out.println(Character.toUpperCase(ch));
}
}
输出结果:
a
---------------------------------
isUpperCase():true
isUpperCase():false
isUpperCase():false
---------------------------------
isLowerCase():false
isLowerCase():true
isLowerCase():false
---------------------------------
isDigit():false
isDigit():false
isDigit():true
五.日历类—Calendar
package calendar_05;
import java.util.Calendar;
/**
* @Date 2021/7/28
*
* 日历类:java.util.Calendar
*
* Calendar:提供一些诸如 获取年,月,月中的日期 等等字段值
* 抽象类,不能实例化
* 如果一个类没有抽象方法,这个类可不可以定义为抽象类? 可以,为了不能实例化,通过子类间接实例化
*
*
* 不能实例化:
* 静态功能,返回值是它自己本身
* public static Calendar getInstance()
*
*
* 成员方法:
* public int get(int field):根据给定日历字段----获取日历字段的值(系统的日历)
*
* public abstract void add(int field,int amount):给指定的日历字段,添加或者减去时间偏移量
* 参数1:日历字段
* 参数2:偏移量
*
*/
public class CalendarDemo {
public static void main(String[] args) {
//创建日历类对象
//获取系统的年月日
// Calendar c = new Calendar() ;
//public static Calendar getInstance()
Calendar calendar = Calendar.getInstance();
// System.out.println(calendar);
//获取年
//public static final int YEAR
int year = calendar.get(Calendar.YEAR) ;
//获取月:
//public static final int MONTH:0-11之间
int month = calendar.get(Calendar.MONTH) ;
//获取月中的日期
//public static final int DATE
//public static final int DAY OF MONTH : 每个月的第一天1
int date = calendar.get(Calendar.DATE) ;
System.out.println("当前日历为:"+year+"年"+(month+1)+"月"+date+"日");
System.out.println("------------------------------------------------");
//获取3年前的今天
//给year设置偏移量
// public abstract void add(int field,int amount)
calendar.add(Calendar.YEAR,-3);
//获取
year = calendar.get(Calendar.YEAR) ;
System.out.println("当前日历为:"+year+"年"+(month+1)+"月"+date+"日");
/* //5年后的十天前
//需求:键盘录入一个年份,算出任意年份的2月份有多少天 (不考虑润月)*/
}
}
输出结果:
当前日历为:2021年8月6日
------------------------------------------------
当前日历为:2018年8月6日
?六.java.util.Date的两种应用方法:
1.基础应用:
package date_06;
import java.util.Date;
/**
* java.util.Date:表示特定瞬间,精确到毫秒!
* 它还允许格式化和解析日期字符串
*
* 构造方法:
* public Date():当前系统时间格式
* public Date(long date):参数为 时间毫秒值---->Date对象 (1970年1月1日...)
*/
public class DateDemo {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);//输出结果:Wed Jul 28 20:09:05 CST 2021
System.out.println("--------------------------");
long time = 60*60;
Date date1 = new Date(time);
System.out.println(date1);//输出结果:Thu Jan 01 08:00:03 CST 1970
}
}
2.Date和String的相互转换
1)java.util.Date-----String ?格式化过程;
2)String:日期文本----->Date 解析过程。
例子:
package date_06;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Date 2021/7/28
* java.util.Date-----String 格式化过程
*
* DateForamt:抽象类----提供具体的日期/格式化的子类:SimpleDateFormat
* format(Date对象)--->String
*
* SimpleDateFormat:构造函数
* public SimpleDateFormat():使用默认模式
* public SimpleDateFormat(String pattern):使用指定的模式进行解析或者格式 (推荐)
* 参数:
* 一种模式
* 表示年 "yyyy"
* 表示月 "MM"
* 表示月中的日期 "dd"
* 一天中小时数 "HH"
* 分钟数 "mm"
* 秒数 "ss"
*
*
* String:日期文本----->Date
* 解析过程
*
* public Date parse(String source)throws ParseException
* 如果解析的字符串的格式和 public SimpleDateFormat(String pattern)的参数模式不匹配的话,就会出现解析异常!
*/
public class DateDemo2 {
public static void main(String[] args) throws ParseException {
//date格式化成String
//1)创建date对象,表示当前时间
Date date = new Date();
//2)创建SimpleDateFormat对象(中间桥梁)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//3)调用format格式化
sdf.format(date);
String strDate = sdf.format(date);
System.out.println(date);//作为对比
System.out.println(strDate);//输出格式化后的日期\
//输出结果;Wed Jul 28 20:53:04 CST 2021 对比项
// 2021-07-28 20:53:04 格式化后结果
System.out.println("-------------------------------------");
//String 解析成 Date格式 (重点)
//1)创建一个String日期文本
//2)创建SimpleDateFormat对象指定一个格式
//3)调用parse方法进行解析
//注意:SimpleDateFormat解析模式输入的格式必须和String日期文本格式一样,否则会报错
String string = "2015-09-01";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
//public Date parse(String source)throws ParseException 就是parse方法的具体写法
sdf1.parse(string); //会报错然后,Alt+Enter(回车键)纠错
Date date2 = sdf1.parse(string);
System.out.println(date2);
//输出结果;Tue Sep 01 00:00:00 CST 2015
}
}
第四天
一.
1.针对java.util.Date日期对象和String:日期文本字符串进行相互转换的工具类
package dateutils_01;
/* 这是针对java.util.Date日期对象和String:日期文本字符串进行相互转换的工具类*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
public class DateUtils {
//构造私有化方法
private DateUtils(){}
//提供两个静态化功能
//date格式化成String
/**
* 这个方法是针对将日期对象转换成日期文本字符串
* @param date 需要被格式化的日期对象
* @param pattern 需要指定的模式 pattern "yyyy-MM-dd HH:mm:ss"
* @return 返回的日期文本字符串 结果 yyyy-MM-dd
* 方法是:format
*/ ( 类的对象, 模式)
public static String datetoString(Date date, String pattern){
//方法一:分步走
/* SimpleDateFormat sdf =new SimpleDateFormat(pattern);
String result = sdf.format(date);
return result;*/
//方法二:一步走
return new SimpleDateFormat(pattern).format(date);
}
//String--->Date: 解析过程: parse(String source) throws ParseException
/**
* 这个方法针对String日期文本字符串转换成日期对象
* @param source 需要被解析的日期文本字符串
* @param pattern 需要解析中使用的一种模式
* @return 返回的就是日期对象Date
* 方法是:parse
*/
public static Date stringtoDate(String source,String pattern) throws ParseException {
return new SimpleDateFormat(pattern).parse(source);
}
}
class Test{
public static void main(String[] args) throws ParseException {
//直接使用工具类测试
//Date---->String 格式化
Date date = new Date();
String str = DateUtils.datetoString(date,"yyyy-MM-dd HH:mm:ss" );
System.out.println(str);
//String--->Date 解析
String source = "2015-09-01";
Date date1 = DateUtils.stringtoDate(source, "yyyy-MM-dd");
System.out.println(date1);
}
}
输出结果:
2021-07-29 21:07:58
Tue Sep 01 00:00:00 CST 2
2. (1)Random类产生随机数
package random_02;
import java.math.RoundingMode;
import java.util.Random;
/**
* @Date 2021/7/29
* java.util.Random类:
* 伪随机数生成器
*
* 构造方法
* public Random(): 产生一个随机生成器对象,通过成员方法随机数每次没不一样的(推荐)
* public Random(long seed) :参数为long类型的值(随机数流:种子),每次通过成员方法获取随机数产生的随机数相同的
*
* 获取随机数的成员方法
* public int nextInt():获取的值的范围是int类型的取值范围(-2的31次方到2的31次方-1)
* public int nextInt(int n):获取的0-n之间的数据 (不包含n)
*
* 产生随机数:
* Math类的random方法
* public static double random();
*
* Random类:也能够去使用
* 无参构造方法 + 成员方法
* public Random():+ public int nextInt(int n)
*
*/
public class RandomDome {
public static void main(String[] args) {
//创建一个随机数生成器
/* //public Random(long seed): 构造方法
Random random = new Random(1323214);*/
//public Random(): 构造方法
//每次通过随机数生成器产生的随机不同
Random random = new Random();
//产生10个随机数
for (int x = 0; x < 10; x++) {
/* //使用public int nextInt(): 成员方法
int num = random.nextInt();
System.out.println(num);*/
//public int nextInt(int n): 成员方法
int num = random.nextInt(60+1);
System.out.println(num);
}
}
}
输出结果:
38
0
22
44
39
58
8
27
25
33
2.(2)java.lang.Math :针对数学运算的工具类,提供了很多方法,以下为某些运算方法
package random_02;
/**
* @Date 2021/7/29
* java.lang.Math :针对数学运算的工具类,提供了很多方法
* public static int abs(int a):绝对值方法
* public static double ceil(double a):向上取整
* public static double floor(double a):向下取整
* public static int max(int a,int b):获取最大值
* public static int min(int a,int b):获取最小值
* public static double pow(double a,double b):a的b次幂
* public static double random():[0.0,1.0):随机数
* public static long round(double a):四舍五入
* public static double sqrt(double a):开平方根
*
* Math类中的功能都是静态的,里面构造方法私有了!
*
* 一般情况:工具类中构造方法都是会私有化(自定义的工具类),提供对外静态的公共访问方法
* (Java设计模式:单例模式)
*/
public class MathDome {
public static void main(String[] args) {
// public static int abs(int a): 绝对值方法
System.out.println(Math.abs(-10));
//public static double ceil(double a):向上取整
System.out.println(Math.ceil(16.67));
//public static double floor(double a):向下取整
System.out.println(Math.floor(13.39));
//public static int max(int a,int b):获取最大值
System.out.println(Math.max(Math.max(10,20),50));//求三个数,使用方法嵌套
//public static double pow(double a,double b):a的b次幂
System.out.println(Math.pow(2,5));
//public static long round(double a):四舍五入
System.out.println(Math.round(21.58));
//public static double sqrt(double a):开平方根
System.out.println(Math.sqrt(9));
}
}
输出结果;
10
17.0
13.0
50
32.0
22
3.0
2.(3)Math类的功能都是静态的,就可以使用静态导入(前提不能和其他方法名重名)
格式:import static 包名.类名.方法名;
package random_02;
/**
* @Date 2021/7/29
* JDK5的静态导入特性,必须方法静态的(导入到方法的级别)
*
*Math类的功能都是静态的,就可以使用静态导入
* import static 包名.类名.方法名;
*
* 前提不能和其他方法名重名;
*/
import java.util.Scanner ;//导入到类的级别
import static java.lang.Math.abs; //导入到方法的级别
import static java.lang.Math.random;
public class MathTest {
public static void main(String[] args) {
System.out.println(abs(-10));//使用他的前提是需要先导包
// System.out.println(java.lang.Math.abs(-10)); 和下面那个自定义的方法配合使用
System.out.println(random()*100+1);//同理,需要先导包
}
/*//自定义abs方法,该方法和上面的import static java.lang.Math.abs;重名了,
// 会导致直接输出a为-10这个结果
public static int abs(int a){ //默认就是使用当前abs方法,并不是Math提供的
return a;
}*/
}
输出结果:
10
90.29564592195919
3. JDK提供的BigDecimal类进行小数的精确计算
package bigdecimal_03;
import java.math.BigDecimal;
/**
* @Date 2021/7/29
*
* 小数要进行精确计算-还可以计算的同时保留小数点后的有效位数
* Java提供的类: BigDecimal
*
* 构造方法
* public BigDecimal(String value):数字字符串
*
* 成员方法:
* public BigDecimal add(BigDecimal augend)加
* public BigDecimal subtract(BigDecimal subtrahend)减
* public BigDecimal multiply(BigDecimal multiplicand)乘
* public BigDecimal divide(BigDecimal divisor):除
*
* public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)
* 参数1:商
* 参数2:小数点后保留的有效位数
* 参数3:舍入模式 :四舍五入
*/
public class BigDecimalDemo {
public static void main(String[] args) {
//创建BigDecimal对象
BigDecimal bd1 =new BigDecimal("1.36"); // 也需要先导包
BigDecimal bd2 =new BigDecimal("3.80");
BigDecimal bd3 =new BigDecimal("6.05");
BigDecimal bd4 =new BigDecimal("0.85");
System.out.println(bd1.add(bd2));//加
System.out.println(bd1.subtract(bd2));//减
System.out.println(bd1.multiply(bd2));//乘
// System.out.println(bd3.divide(bd4));//不保留(整除)
System.out.println(bd3.divide(bd4,3,BigDecimal.ROUND_HALF_UP));//四十五入
}
}
输出结果:
5.16
-2.44
5.1680
7.118
|