05-Java进阶-String类、静态static关键字、Arrays工具类、math类
05-常用API-Scanner类、Random类、ArrayList类
1 Scanner类
1.1 API的概述与使用步骤
- 打开帮助文档。 2. 点击显示,找到索引,看到输入框。 3. 你要找谁?在输入框里输入,然后回车。 4. 看包。java.lang下的类不需要导包,其他需要。 5. 看类的解释和说明。 6. 学习构造方法。7. 使用成员方法。
1.2 Scanner的使用及其API文档
Scanner类的功能:可以实现键盘输入数据,到程序当中。
引用类型的一般使用步骤:
- 导包
import 包路径.类名称;
如果需要使用的目标类,和当前类位于同一个包下,则可以省略导包语句不写。
只有java.lang包下的内容不需要导包,其他的包都需要import语句。 - 创建
类名称 对象名 = new 类名称(); - 使用
对象名.成员方法名()
获取键盘输入的一个int数字:int num = sc.nextInt();
获取键盘输入的一个字符串:String str = sc.next();
ps:运行后的显示框左侧出现红色方框说明程序等待键盘输入,显示框中绿色字体代表键盘输入的值,黑色字体代表程序输出的值
import java.util.Scanner; // 1. 导包 public class Demo01Scanner { public static void main(String[] args) { // 2. 创建对象 // 备注:System.in代表从键盘进行输入 Scanner sc = new Scanner(System.in); // 3. 获取键盘输入的int数字 int num = sc.nextInt(); System.out.println("输入的int数字是:" + num); // 4. 获取键盘输入的字符串 String str = sc.next(); System.out.println("输入的字符串是:" + str); } }
1.3 Scanner练习:键盘输入两个int数,求和
题目:
键盘输入两个int数字,并且求出和值。
思路:
- 既然需要键盘输入,那么就用Scanner。
- Scanner的三个步骤:导包、创建、使用
- 需要的是两个数字,所以要调用两次nextInt方法
- 得到了两个数字,就需要加在一起。
- 将结果打印输出。
import java.util.Scanner; public class Demo02ScannerSum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入第一个数字:"); int a = sc.nextInt(); System.out.println("请输入第二个数字:"); int b = sc.nextInt(); int result = a + b; System.out.println("结果是:" + result); } }
1.4 Scanner练习:键盘输入3个int数,求最大值
题目:
键盘输入三个int数字,然后求出其中的最大值。
思路:
- 既然是键盘输入,肯定需要用到Scanner
- Scanner三个步骤:导包、创建、使用nextInt()方法
- 既然是三个数字,那么调用三次nextInt()方法,得到三个int变量
- 无法同时判断三个数字谁最大,应该转换成为两个步骤:
4.1 首先判断前两个当中谁最大,拿到前两个的最大值
4.2 拿着前两个中的最大值,再和第三个数字比较,得到三个数字当中的最大值 - 打印最终结果
import java.util.Scanner; public class Demo03ScannerMax { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入第一个数字:"); int a = sc.nextInt(); System.out.println("请输入第二个数字:"); int b = sc.nextInt(); System.out.println("请输入第三个数字:"); int c = sc.nextInt(); // 首先得到前两个数字当中的最大值 int temp = a > b ? a : b; int max = temp > c ? temp : c; System.out.println("最大值是:" + max); } }
2 匿名对象
2.1 匿名对象的说明
public class Person { String name; public void showName() { System.out.println("我叫:" + name); } }
创建对象的标准格式:
类名称 对象名 = new 类名称();
匿名对象就是只有右边的对象,没有左边的名字和赋值运算符。
new 类名称();
注意事项:匿名对象只能使用唯一的一次,下次再用不得不再创建一个新对象。
使用建议:如果确定有一个对象只需要使用唯一的一次,就可以用匿名对象。
public class Demo01Anonymous { public static void main(String[] args) { // 左边的one就是对象的名字 Person one = new Person(); one.name = "高圆圆"; one.showName(); // 我叫高圆圆 System.out.println("==============="); // 匿名对象 new Person().name = "赵又廷"; //把“赵又廷”赋值交给匿名对象中的一个成员变量name new Person().showName(); // 我叫:null //结果不是赵又廷是因为这个有new,说明又是一个全新的对象 } }
2.2 匿名对象作为方法的参数
import java.util.Scanner; public class Demo02Anonymous { public static void main(String[] args) { // 普通使用方式 // Scanner sc = new Scanner(System.in); // int num = sc.nextInt(); // 匿名对象的方式 // int num = new Scanner(System.in).nextInt(); // 没有sc名称,直接new完了.方法调用,只能用一次 // System.out.println("输入的是:" + num); // 调用methodParam方法,使用一般写法传入参数 // Scanner sc = new Scanner(System.in); // methodParam(sc); /* 调用methodParam方法,使用匿名对象来进行传参,new了Scanner拿进方法里, 然后sc就能够拿到Scanner,方法里面就可以随便用sc. */ // methodParam(new Scanner(System.in)); Scanner sc = methodReturn(); /*单独调用methodReturn,methodReturn();后alt+回车选择introduce local variable,取名sc 调用methodReturn,就可以把new出来的 Scanner(System.in)匿名对象作为返回值交给sc*/ int num = sc.nextInt(); System.out.println("输入的是:" + num); } //匿名对象作为方法的参数,参数类型为Scanner sc public static void methodParam(Scanner sc) { int num = sc.nextInt(); System.out.println("输入的是:" + num); } //匿名对象作为方法的返回值 public static Scanner methodReturn() { // Scanner sc = new Scanner(System.in); // return sc; return new Scanner(System.in); } }
3 Random类
3.1 Random概述及基本使用
Random类用来生成随机数字。使用起来也是三个步骤:
- 导包
import java.util.Random; - 创建
Random r = new Random(); // 小括号当中留空即可 - 使用
获取一个随机的int数字(范围是int所有范围,有正负两种):int num = r.nextInt()
获取一个随机的int数字(参数代表了范围,左闭右开区间):int num = r.nextInt(3)
实际上代表的含义是:[0,3),也就是0~2
import java.util.Random; public class Demo01Random { public static void main(String[] args) { Random r = new Random(); int num = r.nextInt(); System.out.println("随机数是:" + num); } }
举例
import java.util.Random; public class Demo02Random { public static void main(String[] args) { Random r = new Random(); for (int i = 0; i < 100; i++) { int num = r.nextInt(10); // 范围实际上是0~9 System.out.println(num); } } }
3.2 练习:生成[1,n]之间的随机数字
题目要求:
根据int变量n的值,来获取随机数字,范围是[1,n],可以取到1也可以取到n。
思路:
- 定义一个int变量n,随意赋值
- 要使用Random:三个步骤,导包、创建、使用
- 如果写10,那么就是09,然而想要的是110,可以发现:整体+1即可。
- 打印随机数字
import java.util.Random; public class Demo03Random { public static void main(String[] args) { int n = 5; Random r = new Random(); for (int i = 0; i < 100; i++) { // 本来范围是[0,n),整体+1之后变成了[1,n+1),也就是[1,n] int result = r.nextInt(n) + 1; System.out.println(result); } } }
3.3 练习:Random猜数字小游戏
题目:
用代码模拟猜数字的小游戏。
思路:
- 首先需要产生一个随机数字,并且一旦产生不再变化。用Random的nextInt方法
- 需要键盘输入,所以用到了Scanner
- 获取键盘输入的数字,用Scanner当中的nextInt方法(Scanner当中的nextInt方法负责键盘输入,而Random当中的nextInt方法负责生成随机数字)
- 已经得到了两个数字,判断(if)一下:
如果太大了,提示太大,并且重试;
如果太小了,提示太小,并且重试;
如果猜中了,游戏结束。 - 重试就是再来一次,循环次数不确定,用while(true)死循环。
import java.util.Random; import java.util.Scanner; public class Demo04RandomGame { public static void main(String[] args) { Random r = new Random(); int randomNum = r.nextInt(100) + 1; // [1,100] Scanner sc = new Scanner(System.in); while (true) { System.out.println("请输入你猜测的数字:"); int guessNum = sc.nextInt(); // 键盘输入猜测的数字 if (guessNum > randomNum) { System.out.println("太大了,请重试。"); } else if (guessNum < randomNum) { System.out.println("太小了,请重试。"); } else { System.out.println("恭喜你,猜中啦!"); break; // 如果猜中,不再重试 } } System.out.println("游戏结束。"); } }
4 ArrayList集合
4.1 对象数组
public class Person { private String name; private int age; public Person() { } public Person(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; } }
题目:
定义一个数组,用来存储3个Person对象。
数组有一个缺点:一旦创建,程序运行期间长度不可以发生改变。
public class Demo01Array { public static void main(String[] args) { // 首先创建一个长度为3的数组,里面用来存放Person类型的对象 Person[] array = new Person[3]; Person one = new Person("迪丽热巴", 18); Person two = new Person("古力娜扎", 28); Person three = new Person("玛尔扎哈", 38); // 将one当中的地址值赋值到数组的0号元素位置 array[0] = one; array[1] = two; array[2] = three; System.out.println(array[0]); // 地址值 System.out.println(array[1]); // 地址值 System.out.println(array[2]); // 地址值 System.out.println(array[1].getName()); // 古力娜扎 } }
4.2 ArrayList集合概述和基本使用
数组的长度不可以发生改变。
但是ArrayList集合的长度是可以随意变化的。
对于ArrayList来说,有一个尖括号代表泛型。
泛型:也就是装在集合当中的所有元素,全都是统一的什么类型。
注意:泛型只能是引用类型,不能是基本类型。
注意事项:
对于ArrayList集合来说,直接打印得到的不是地址值,而是内容。
如果内容是空,得到的是空的中括号:[]
import java.util.ArrayList; public class Demo02ArrayList { public static void main(String[] args) { // 创建了一个ArrayList集合,集合的名称是list,里面装的全都是String字符串类型的数据 // 备注:从JDK 1.7+开始,右侧的尖括号内部可以不写内容,但是<>本身还是要写的。 ArrayList<String> list = new ArrayList<>(); System.out.println(list); // [] // 向集合当中添加一些数据,需要用到add方法。 list.add("赵丽颖"); System.out.println(list); // [赵丽颖] list.add("迪丽热巴"); list.add("古力娜扎"); list.add("玛尔扎哈"); System.out.println(list); // [赵丽颖, 迪丽热巴, 古力娜扎, 玛尔扎哈] // list.add(100); // 错误写法!因为创建的时候尖括号泛型已经说了是字符串,添加进去的元素就必须都是字符串才行 } }
4.3 Arraylist集合常用方法
ArrayList当中的常用方法有:
public boolean add(E e):向集合当中添加元素,参数的类型和泛型一致。返回值代表添加是否成功。
备注:对于ArrayList集合来说,add添加动作一定是成功的,所以返回值可用可不用。
但是对于其他集合(今后学习)来说,add添加动作不一定成功。
public E get(int index):从集合当中获取元素,参数是索引编号,返回值就是对应位置的元素。
public E remove(int index):从集合当中删除元素,参数是索引编号,返回值就是被删除掉的元素。
public int size():获取集合的尺寸长度,返回值是集合中包含的元素个数。
import java.util.ArrayList; public class Demo03ArrayListMethod { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); System.out.println(list); // [] // 向集合中添加元素:add boolean success = list.add("柳岩"); System.out.println(list); // [柳岩] System.out.println("添加的动作是否成功:" + success); // true list.add("高圆圆"); list.add("赵又廷"); list.add("李小璐"); list.add("贾乃亮"); System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 李小璐, 贾乃亮] // 从集合中获取元素:get。索引值从0开始 String name = list.get(2); System.out.println("第2号索引位置:" + name); // 赵又廷 // 从集合中删除元素:remove。索引值从0开始。 String whoRemoved = list.remove(3); System.out.println("被删除的人是:" + whoRemoved); // 李小璐 System.out.println(list); // [柳岩, 高圆圆, 赵又廷, 贾乃亮] // 获取集合的长度尺寸,也就是其中元素的个数 int size = list.size(); System.out.println("集合的长度是:" + size); } }
遍历ArrayList集合
import java.util.ArrayList; public class Demo04ArrayListEach { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("迪丽热巴"); list.add("古力娜扎"); list.add("玛尔扎哈"); // 遍历集合 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } }
4.4 ArrayList集合存储基本数据
如果希望向集合ArrayList当中存储基本类型数据,必须使用基本类型对应的“包装类”。
基本类型 包装类(引用类型,包装类都位于java.lang包下)
byte Byte
short Short
int Integer 【特殊】
long Long
float Float
double Double
char Character 【特殊】
boolean Boolean
从JDK 1.5+开始,支持自动装箱、自动拆箱。
自动装箱:基本类型 --> 包装类型
自动拆箱:包装类型 --> 基本类型
import java.util.ArrayList; public class Demo05ArrayListBasic { public static void main(String[] args) { ArrayList<String> listA = new ArrayList<>(); // 错误写法!泛型只能是引用类型,不能是基本类型 // ArrayList<int> listB = new ArrayList<>(); ArrayList<Integer> listC = new ArrayList<>(); listC.add(100); listC.add(200); System.out.println(listC); // [100, 200] int num = listC.get(1); System.out.println("第1号元素是:" + num); } }
4.5 ArrayList练习
(1)存储随机
题目:
生成6个1~33之间的随机整数,添加到集合,并遍历集合。
思路:
- 需要存储6个数字,创建一个集合,
- 产生随机数,需要用到Random
- 用循环6次,来产生6个随机数字:for循环
- 循环内调用r.nextInt(int n),参数是33,032,整体+1才是133
- 把数字添加到集合中:add
- 遍历集合:for、size、get
import java.util.ArrayList; import java.util.Random; public class Demo01ArrayListRandom { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); Random r = new Random(); for (int i = 0; i < 6; i++) { int num = r.nextInt(33) + 1; list.add(num); } // 遍历集合 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } }
(2)存储自定义学生对象
题目:
自定义4个学生对象,添加到集合,并遍历。
思路:
- 自定义Student学生类,四个部分。
- 创建一个集合,用来存储学生对象。泛型:
- 根据类,创建4个学生对象。
- 将4个学生对象添加到集合中:add
- 遍历集合:for、size、get
public class Student { 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; } }
public class Demo02ArrayListStudent { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<>(); Student one = new Student("洪七公", 20); Student two = new Student("欧阳锋", 21); Student three = new Student("黄药师", 22); Student four = new Student("段智兴", 23); list.add(one); list.add(two); list.add(three); list.add(four); // 遍历集合 for (int i = 0; i < list.size(); i++) { Student stu = list.get(i); System.out.println("姓名:" + stu.getName() + ",年龄" + stu.getAge()); } } }
(3)以指定格式打印集合
题目:
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用{}扩起集合,使用@分隔每个元素。
格式参照 {元素@元素@元素}。
System.out.println(list); [10, 20, 30]
printArrayList(list); {10@20@30}
public class Demo03ArrayListPrint { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("张三丰"); list.add("宋远桥"); list.add("张无忌"); list.add("张翠山"); System.out.println(list); // [张三丰, 宋远桥, 张无忌, 张翠山] printArrayList(list); } /* 定义方法的三要素 返回值类型:只是进行打印而已,没有运算,没有结果;所以用void 方法名称:printArrayList 参数列表:ArrayList */ public static void printArrayList(ArrayList<String> list) { // {10@20@30} System.out.print("{"); for (int i = 0; i < list.size(); i++) { String name = list.get(i); if (i == list.size() - 1) { System.out.println(name + "}"); } else { System.out.print(name + "@"); } } } }
(4)筛选集合
题目:
用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中。
要求使用自定义的方法来实现筛选。
分析:
- 需要创建一个大集合,用来存储int数字:
- 随机数字就用Random nextInt
- 循环20次,把随机数字放入大集合:for循环、add方法
- 定义一个方法,用来进行筛选。
筛选:根据大集合,筛选符合要求的元素,得到小集合。
三要素
返回值类型:ArrayList小集合(里面元素个数不确定)
方法名称:getSmallList
参数列表:ArrayList大集合(装着20个随机数字) - 判断(if)是偶数:num % 2 == 0
- 如果是偶数,就放到小集合当中,否则不放。
public class Demo04ArrayListReturn { public static void main(String[] args) { ArrayList<Integer> bigList = new ArrayList<>(); Random r = new Random(); for (int i = 0; i < 20; i++) { int num = r.nextInt(100) + 1; // 1~100 bigList.add(num); } ArrayList<Integer> smallList = getSmallList(bigList); System.out.println("偶数总共有多少个:" + smallList.size()); for (int i = 0; i < smallList.size(); i++) { System.out.println(smallList.get(i)); } } // 这个方法,接收大集合参数,返回小集合结果。集合既可以作为参数,又可以作为返回值,如果是作为参数,则传递进去的就是地址值,如果是返回值,返还回来的也是地址值。 public static ArrayList<Integer> getSmallList(ArrayList<Integer> bigList) { // 创建一个小集合,用来装偶数结果 ArrayList<Integer> smallList = new ArrayList<>(); for (int i = 0; i < bigList.size(); i++) { int num = bigList.get(i); if (num % 2 == 0) { smallList.add(num); } } return smallList; } }
5 String类
5.1 字符串特点及创建方式
java.lang.String类代表字符串。
API当中说:Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。
其实就是说:程序当中所有的双引号字符串,都是String类的对象。(就算没有new,也照样是。)
字符串的特点:
- 字符串的内容永不可变。【重点】
- 正是因为字符串不可改变,所以字符串是可以共享使用的。
- 字符串效果上相当于是char[]字符数组,但是底层原理是byte[]字节数组。
创建字符串的常见3+1种方式
三种构造方法:
public String():创建一个空白字符串,不含有任何内容。
public String(char[] array):根据字符数组的内容,来创建对应的字符串。
public String(byte[] array):根据字节数组的内容,来创建对应的字符串。
一种直接创建:
String str = “Hello”; // 右边直接用双引号
注意:直接写上双引号,就是字符串对象。
public class Demo01String { public static void main(String[] args) { // 使用空参构造 String str1 = new String(); // 小括号留空,说明字符串什么内容都没有。 System.out.println("第1个字符串:" + str1); // 根据字符数组创建字符串 char[] charArray = { 'A', 'B', 'C' }; String str2 = new String(charArray); System.out.println("第2个字符串:" + str2); // 根据字节数组创建字符串 byte[] byteArray = { 97, 98, 99 }; String str3 = new String(byteArray); System.out.println("第3个字符串:" + str3); // 直接创建 String str4 = "Hello"; System.out.println("第4个字符串:" + str4); } }
5.2 字符串的常量池
字符串常量池:程序当中直接写上的双引号字符串,就在字符串常量池中。
对于基本类型来说,==是进行数值的比较。
对于引用类型来说,==是进行【地址值】的比较。
public class Demo02StringPool { public static void main(String[] args) { String str1 = "abc"; String str2 = "abc"; char[] charArray = {'a', 'b', 'c'}; String str3 = new String(charArray); System.out.println(str1 == str2); // true System.out.println(str1 == str3); // false System.out.println(str2 == str3); // false } }
内存图
5.3 字符串的比较相关方法
==是进行对象的地址值比较,如果确实需要字符串的内容比较,可以使用两个方法:
public boolean equals(Object obj):参数可以是任何对象,只有参数是一个字符串并且内容相同的才会给true;否则返回false。
注意事项:
- 任何对象都能用Object进行接收。
- equals方法具有对称性,也就是a.equals(b)和b.equals(a)效果一样。
- 如果比较双方一个常量一个变量,推荐把常量字符串写在前面。
推荐:“abc”.equals(str) 不推荐:str.equals(“abc”)
public boolean equalsIgnoreCase(String str):忽略大小写,进行内容比较。
public class Demo01StringEquals { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Hello"; char[] charArray = {'H', 'e', 'l', 'l', 'o'}; String str3 = new String(charArray); System.out.println(str1.equals(str2)); // true System.out.println(str2.equals(str3)); // true System.out.println(str3.equals("Hello")); // true System.out.println("Hello".equals(str1)); // true a.equals(b)和b.equals(a)效果一样。 String str4 = "hello"; System.out.println(str1.equals(str4)); // false System.out.println("================="); String str5 = null; System.out.println("abc".equals(str5)); // 推荐:false // System.out.println(str5.equals("abc")); // 不推荐:报错,空指针异常NullPointerException System.out.println("================="); String strA = "Java"; String strB = "java"; System.out.println(strA.equals(strB)); // false,严格区分大小写 System.out.println(strA.equalsIgnoreCase(strB)); // true,忽略大小写 // 注意,只有英文字母区分大小写,其他都不区分大小写 System.out.println("abc一123".equalsIgnoreCase("abc壹123")); // false } }
5.4 字符串的获取相关方法
String当中与获取相关的常用方法有:
public int length():获取字符串当中含有的字符个数,拿到字符串长度。
public String concat(String str):将当前字符串和参数字符串拼接成为返回值新的字符串。
public char charAt(int index):获取指定索引位置的单个字符。(索引从0开始。)
public int indexOf(String str):查找参数字符串在本字符串当中首次出现的索引位置,如果没有返回-1值。
public class Demo02StringGet { public static void main(String[] args) { // 获取字符串的长度 int length = "asdasfeutrvauevbueyvb".length(); System.out.println("字符串的长度是:" + length); // 拼接字符串 String str1 = "Hello"; String str2 = "World"; String str3 = str1.concat(str2); System.out.println(str1); // Hello,原封不动 System.out.println(str2); // World,原封不动 System.out.println(str3); // HelloWorld,新的字符串 System.out.println("=============="); // 获取指定索引位置的单个字符 char ch = "Hello".charAt(1); System.out.println("在1号索引位置的字符是:" + ch); System.out.println("=============="); // 查找参数字符串在本来字符串当中出现的第一次索引位置 // 如果根本没有,返回-1值 String original = "HelloWorldHelloWorld"; int index = original.indexOf("llo"); System.out.println("第一次索引值是:" + index); // 2 System.out.println("HelloWorld".indexOf("abc")); // -1 } }
5.5 字符串的截取方法
字符串的截取方法:
public String substring(int index):截取从参数位置一直到字符串末尾,返回新字符串。
public String substring(int begin, int end):截取从begin开始,一直到end结束,中间的字符串。
备注:[begin,end),包含左边,不包含右边。
public class Demo03Substring { public static void main(String[] args) { String str1 = "HelloWorld"; String str2 = str1.substring(5); System.out.println(str1); // HelloWorld,原封不动 System.out.println(str2); // World,新字符串 System.out.println("================"); String str3 = str1.substring(4, 7); System.out.println(str3); // oWo System.out.println("================"); // 下面这种写法,字符串的内容仍然是没有改变的 // 下面有两个字符串:"Hello","Java" // strA当中保存的是地址值。 // 本来地址值是Hello的0x666, // 后来地址值变成了Java的0x999 String strA = "Hello"; System.out.println(strA); // Hello strA = "Java"; System.out.println(strA); // Java } }
5.6 字符串的转换相关方法
String当中与转换相关的常用方法有:
public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。
public byte[] getBytes():获得当前字符串底层的字节数组。
public String replace(CharSequence oldString, CharSequence newString):
将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。
备注:CharSequence意思就是说可以接受字符串类型。
public class Demo04StringConvert { public static void main(String[] args) { // 转换成为字符数组 char[] chars = "Hello".toCharArray(); System.out.println(chars[0]); // H System.out.println(chars.length); // 5 System.out.println("=============="); // 转换成为字节数组 byte[] bytes = "abc".getBytes(); for (int i = 0; i < bytes.length; i++) { System.out.println(bytes[i]); } System.out.println("=============="); // 字符串的内容替换 String str1 = "How do you do?"; String str2 = str1.replace("o", "*"); System.out.println(str1); // How do you do? System.out.println(str2); // H*w d* y*u d*? System.out.println("=============="); String lang1 = "会不会玩儿呀!你大爷的!你大爷的!你大爷的!!!"; String lang2 = lang1.replace("你大爷的", "****"); System.out.println(lang2); // 会不会玩儿呀!****!****!****!!! } }
5.7 字符串的分割方法
分割字符串的方法:
public String[] split(String regex):按照参数的规则,将字符串切分成为若干部分。
注意事项:
split方法的参数其实是一个“正则表达式”,今后学习。
今天要注意:如果按照英文句点“.”进行切分,必须写"\\ ."(两个反斜杠)
public class Demo05StringSplit { public static void main(String[] args) { String str1 = "aaa,bbb,ccc"; String[] array1 = str1.split(","); for (int i = 0; i < array1.length; i++) { System.out.println(array1[i]); } System.out.println("==============="); String str2 = "aaa bbb ccc"; String[] array2 = str2.split(" "); for (int i = 0; i < array2.length; i++) { System.out.println(array2[i]); } System.out.println("==============="); String str3 = "XXX.YYY.ZZZ"; String[] array3 = str3.split("\\."); System.out.println(array3.length); // 0 for (int i = 0; i < array3.length; i++) { System.out.println(array3[i]); } } }
5.8 String练习
(1)按指定格式拼接内容
题目:
定义一个方法,把数组{1,2,3}按照指定格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。
分析:
- 首先准备一个int[]数组,内容是:1、2、3
- 定义一个方法,用来将数组变成字符串
三要素
返回值类型:String
方法名称:fromArrayToString
参数列表:int[] - 格式:[word1#word2#word3]
用到:for循环、字符串拼接、每个数组元素之前都有一个word字样、分隔使用的是#、区分一下是不是最后一个 - 调用方法,得到返回值,并打印结果字符串
public class Demo06StringPractise { public static void main(String[] args) { int[] array = {1, 2, 3, 4}; String result = fromArrayToString(array); System.out.println(result); } public static String fromArrayToString(int[] array) { String str = "["; for (int i = 0; i < array.length; i++) { if (i == array.length - 1) { str += "word" + array[i] + "]"; } else { str += "word" + array[i] + "#"; } } return str; } }
(2)统计字符串中各种字符出现的次数
题目:
键盘输入一个字符串,并且统计其中各种字符出现的次数。
种类有:大写字母、小写字母、数字、其他
思路:
- 既然用到键盘输入,肯定是Scanner
- 键盘输入的是字符串,那么:String str = sc.next();
- 定义四个变量,分别代表四种字符各自的出现次数。
- 需要对字符串一个字、一个字检查,String–>char[],方法就是toCharArray()
- 遍历char[]字符数组,对当前字符的种类进行判断,并且用四个变量进行++动作。
- 打印输出四个变量,分别代表四种字符出现次数。
public class Demo07StringCount { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串:"); String input = sc.next(); // 获取键盘输入的一个字符串 int countUpper = 0; // 大写字母 int countLower = 0; // 小写字母 int countNumber = 0; // 数字 int countOther = 0; // 其他字符 char[] charArray = input.toCharArray(); for (int i = 0; i < charArray.length; i++) { char ch = charArray[i]; // 当前单个字符 if ('A' <= ch && ch <= 'Z') { countUpper++; } else if ('a' <= ch && ch <= 'z') { countLower++; } else if ('0' <= ch && ch <= '9') { countNumber++; } else { countOther++; } } System.out.println("大写字母有:" + countUpper); System.out.println("小写字母有:" + countLower); System.out.println("数字有:" + countNumber); System.out.println("其他字符有:" + countOther); } }
6 static静态
6.1 静态static关键字概述
6.2 静态static关键字修饰成员变量
public class Student { private int id; // 学号 private String name; // 姓名 private int age; // 年龄 static String room; // 所在教室 private static int idCounter = 0; // 学号计数器,每当new了一个新对象的时候,计数器++ public Student() { this.id = ++idCounter; } public Student(String name, int age) { this.name = name; this.age = age; this.id = ++idCounter; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } }
如果一个成员变量使用了static关键字,那么这个变量不再属于对象自己,而是属于所在的类。多个对象共享同一份数据。
public class Demo01StaticField { public static void main(String[] args) { Student two = new Student("黄蓉", 16); two.room = "101教室"; System.out.println("姓名:" + two.getName() + ",年龄:" + two.getAge() + ",教室:" + two.room + ",学号:" + two.getId()); Student one = new Student("郭靖", 19); System.out.println("姓名:" + one.getName() + ",年龄:" + one.getAge() + ",教室:" + one.room + ",学号:" + one.getId()); } }
6.2 静态static关键字修饰成员方法
public class MyClass { int num; // 成员变量 static int numStatic; // 静态变量 // 成员方法 public void method() { System.out.println("这是一个成员方法。"); // 成员方法可以访问成员变量 System.out.println(num); // 成员方法可以访问静态变量 System.out.println(numStatic); } // 静态方法 public static void methodStatic() { System.out.println("这是一个静态方法。"); // 静态方法可以访问静态变量 System.out.println(numStatic); // 静态不能直接访问非静态【重点】 // System.out.println(num); // 错误写法! // 静态方法中不能使用this关键字。 // System.out.println(this); // 错误写法! } }
一旦使用static修饰成员方法,那么这就成为了静态方法。静态方法不属于对象,而是属于类的。
如果没有static关键字,那么必须首先创建对象,然后通过对象才能使用它。
如果有了static关键字,那么不需要创建对象,直接就能通过类名称来使用它。
无论是成员变量,还是成员方法。如果有了static,都推荐使用类名称进行调用。
静态变量:类名称.静态变量
静态方法:类名称.静态方法()
注意事项:
- 静态不能直接访问非静态。
原因:因为在内存当中是【先】有的静态内容,【后】有的非静态内容。
“先人不知道后人,但是后人知道先人。” - 静态方法当中不能用this。
原因:this代表当前对象,通过谁调用的方法,谁就是当前对象。
public class Demo02StaticMethod { public static void main(String[] args) { MyClass obj = new MyClass(); // 首先创建对象 // 然后才能使用没有static关键字的内容 obj.method(); // 对于静态方法来说,可以通过对象名进行调用,也可以直接通过类名称来调用。 obj.methodStatic(); // 正确,不推荐,这种写法在编译之后也会被javac翻译成为“类名称.静态方法名” MyClass.methodStatic(); // 正确,推荐 // 对于本来当中的静态方法,可以省略类名称 myMethod(); Demo02StaticMethod.myMethod(); // 完全等效 } public static void myMethod() { System.out.println("自己的方法!"); } }
6.3 静态static的内存图
6.4 静态代码块
public class Person { static { System.out.println("静态代码块执行!"); } public Person() { System.out.println("构造方法执行!"); } }
静态代码块的格式是:
public class 类名称 {
static {
// 静态代码块的内容
}
}
特点:当第一次用到本类时,静态代码块执行唯一的一次。
静态内容总是优先于非静态,所以静态代码块比构造方法先执行。
静态代码块的典型用途:
用来一次性地对静态成员变量进行赋值。
public class Demo04Static { public static void main(String[] args) { Person one = new Person(); Person two = new Person(); //静态代码块执行1次,构造方法执行2次 } }
7 Arrays工具类
java.util.Arrays是一个与数组相关的工具类,里面提供了大量静态方法,用来实现数组常见的操作。
public static String toString(数组):将参数数组变成字符串(按照默认格式:[元素1, 元素2, 元素3…])
public static void sort(数组):按照默认升序(从小到大)对数组的元素进行排序。
备注:
- 如果是数值,sort默认按照升序从小到大
- 如果是字符串,sort默认按照字母升序
- 如果是自定义的类型,那么这个自定义的类需要有Comparable或者Comparator接口的支持。(今后学习)
public class Demo01Arrays { public static void main(String[] args) { int[] intArray = {10, 20, 30}; // 将int[]数组按照默认格式变成字符串 String intStr = Arrays.toString(intArray); System.out.println(intStr); // [10, 20, 30] int[] array1 = {2, 1, 3, 10, 6}; Arrays.sort(array1); System.out.println(Arrays.toString(array1)); // [1, 2, 3, 6, 10] String[] array2 = {"bbb", "aaa", "ccc"}; Arrays.sort(array2); System.out.println(Arrays.toString(array2)); // [aaa, bbb, ccc] } }
(1)练习
题目:
请使用Arrays相关的API,将一个随机字符串中的所有字符升序排列,并倒序打印。
public class Demo02ArraysPractise { public static void main(String[] args) { String str = "asv76agfqwdfvasdfvjh"; // 如何进行升序排列:sort // 必须是一个数组,才能用Arrays.sort方法 // String --> 数组,用toCharArray char[] chars = str.toCharArray(); Arrays.sort(chars); // 对字符数组进行升序排列 // 需要倒序遍历 倒序遍历chars.forr 正序遍历chars.fori for (int i = chars.length - 1; i >= 0; i--) { System.out.println(chars[i]); } } }
8 math类
(1)数学工具类
java.util.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作。
public static double abs(double num):获取绝对值。有多种重载。
public static double ceil(double num):向上取整。
public static double floor(double num):向下取整。
public static long round(double num):四舍五入。
Math.PI代表近似的圆周率常量(double)。按住ctrl然后点击math,按ctrl+F12选择
public class Demo03Math { public static void main(String[] args) { // 获取绝对值 System.out.println(Math.abs(3.14)); // 3.14 System.out.println(Math.abs(0)); // 0 System.out.println(Math.abs(-2.5)); // 2.5 System.out.println("================"); // 向上取整 System.out.println(Math.ceil(3.9)); // 4.0 System.out.println(Math.ceil(3.1)); // 4.0 System.out.println(Math.ceil(3.0)); // 3.0 System.out.println("================"); // 向下取整,抹零 System.out.println(Math.floor(30.1)); // 30.0 System.out.println(Math.floor(30.9)); // 30.0 System.out.println(Math.floor(31.0)); // 31.0 System.out.println("================"); System.out.println(Math.round(20.4)); // 20 System.out.println(Math.round(10.5)); // 11 } }
(2)题目:
计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
分析:
- 既然已经确定了范围,for循环
- 起点位置-10.8应该转换成为-10,两种办法:
2.1 可以使用Math.ceil方法,向上(向正方向)取整
2.2 强转成为int,自动舍弃所有小数位 - 每一个数字都是整数,所以步进表达式应该是num++,这样每次都是+1的。
- 如何拿到绝对值:Math.abs方法。
- 一旦发现了一个数字,需要让计数器++进行统计。
备注:如果使用Math.ceil方法,-10.8可以变成-10.0。注意double也是可以进行++的。
public class Demo04MathPractise { public static void main(String[] args) { int count = 0; // 符合要求的数量 double min = -10.8; double max = 5.9; // 这样处理,变量i就是区间之内所有的整数 for (int i = (int) min; i < max; i++) { int abs = Math.abs(i); // 绝对值 if (abs > 6 || abs < 2.1) { System.out.println(i); count++; } } System.out.println("总共有:" + count); // 9 } }
- 农学转IT-Java学习第12天:常用API:String类、static静态、Arrays工具类、Math类
- java自学第4期——:Scanner类、匿名对象介绍、Random类、ArrayList集合、标准类格式、String类、static静态、Arrays工具类、Math类
- java基础语法(八)之String类,static关键字,Arrays类,Math类
- Java基础【String类、static关键字、Arrays类、Math类】
- JAVA基础学习总结,day8(String 类,静态代码块,Arrays类:工具类,Math类:工具类)
- JAVA-5-String类和StringBuffer类、二维数组、形参、冒泡排序及选择排序、Arrays数组工具类
- 黑马程序员——Java基础——集合工具类Collecions、Arrays、其他对象System类、Runtime类、Date类、Calendar类、Math类等操作
- [置顶] Java 8增强的工具类 Arrays(一)
- Java进阶03-final关键字
- Java进阶01 String类
- java集合(工具类Arrays)
- Java进阶01 String类
- 黑马程序员_java基础笔记(05)...String类
- 黑马程序员——java工具类之Collections和Arrays
- day13 java基础(StringBuffer类和Arrays工具类,Integer类)
- Java基础:数组工具类Arrays的用法之Arrays.toString与Arrays.sort
- Java中集合框架工具类——Arrays(传智播客毕老师视频讲解)
- Java基础之集合框架--Arrays工具类(专门操作数组的工具类)
- 黑马程序员_java基础笔记(05)...String类
- 黑马程序员_java基础笔记(05)...String类