java常用类库

来源:互联网 发布:老备案域名出售 编辑:程序博客网 时间:2024/06/16 02:43

Object类

类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。
1.Object类中的常见方法:

A:public String toString():返回对象的字符串表示形式。
注意:默认情况下,返回的是类名+@+十六进制的哈希值组成,意义不大。所以建议重写该方法。
怎么重写呢?
a:手动式
b:自动式 Alt+Shift+S
自动生成。
它的值等价于:
getClass().getName() + ‘@’ + Integer.toHexStrin(hashCode())
Integer:
public static String toHexString(int i)
B:public final Class getClass():返回的是字节码对象,反射的时候讲
C:public int hashCode():返回对象的哈希值。这个值不是实际的地址值,但是可以理解为地址值。
D:protected void finalize():被对象的垃圾回收器调用,用于回收垃圾的。
E:public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。
2.案例

a. toString()方法案例

Student.java()

package object;

public class Student {

private String name;private int age;public Student() {    super();    // TODO Auto-generated constructor stub}public Student(String name, int age) {    super();    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;}@Overridepublic String toString() {    return "Student [name=" + name + ", age=" + age + "]";}

}
StudentDemo.java

package object;

public class StudentDemo {
public static void main(String[] args) {
Student s=new Student();
/**
* 没有重写toString()方法
*/
//System.out.println(s);//object.Student@72ebbf5c
//System.out.println(s.toString());//object.Student@72ebbf5c
//重写toString()方法
System.out.println(s);//Student [name=null, age=0]
System.out.println(s.toString());//Student [name=null, age=0]
}
}
b. equals()方法案例

equals()与==的区别:
==的作用:
比较基本类型:比较的是基本类型的值是否相同。
比较引用类型:比较的是引用类型的地址值是否相同。
public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。
默认情况下,Object类的equals比较的是地址值。
所以,如果你想比较成员变量的值,请重写该方法。
Teacher.java

package object;

public class Teacher {

private String name;private int age;public Teacher() {    super();    // TODO Auto-generated constructor stub}public Teacher(String name, int age) {    super();    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;}@Overridepublic String toString() {    return "Student [name=" + name + ", age=" + age + "]";}@Overridepublic boolean equals(Object obj) {    if (this == obj)        return true;    if (obj == null)        return false;    if (getClass() != obj.getClass())        return false;    Teacher other = (Teacher) obj;    if (age != other.age)        return false;    if (name == null) {        if (other.name != null)            return false;    } else if (!name.equals(other.name))        return false;    return true;}

}
Scanner类

public final class Scanner extends Object implements Iterator
继承Object类,实现Iterator迭代器接口
Scanner用于键盘录入数据
ScannerDemo.java

import java.util.Scanner;

/*
* Scanner用于键盘录入数据:
* Scanner sc = new Scanner(System.in);
*
* 方法:
* public int nextInt();
* public String nextLine();
*/
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
}
}
ScannerDemo1.java

import java.util.Scanner;

/*
* Scanner的小问题。
*
* 先数值类型在String类型有问题。
* 那么怎么解决呢?
* A:把所有的数据全部采用字符串类型接收。然后,要什么就转换为什么。
* B:重写创建一个新的对象。
*/
public class ScannerDemo1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

    // int -- int    // int x = sc.nextInt();    // int y = sc.nextInt();    // String --String    // String x = sc.nextLine();    // String y = sc.nextLine();    // String -- int    // String x = sc.nextLine();    // int y = sc.nextInt();    // int--String    int x = sc.nextInt();    // 重新赋值    sc = new Scanner(System.in);    String y = sc.nextLine();    System.out.println(x);    System.out.println(y);}

}
String类

public final class String extends Object implements Serializable,Comparable, CharSequence
实现了Serializable序列化,Comparable,CharSequence的接口
String 类代表字符串。Java 程序中的所有字符串字面值(如 “abc” )都作为此类的实例实现。
字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。例如:

String str = “abc”;

等效于:

char data[] = {‘a’, ‘b’, ‘c’};

String str = new String(data);

构造方法:

a:String() 空构造创建字符串。
b:String(byte[] bytes) 把字节数组转成字符串
c:String(byte[] bytes, int index, int length) 把字节数组的一部分转成字符串
d:String(char[] value) 把字符数组转成字符串
e:String(char[] value, int index, int count) 把字符数组的一部分转成字符串
f:String(String original) 把字符串转成字符串
StringDemo.java

package string

/*
* 字符串的长度:
* public int length()
*/
public class StringDemo {
public static void main(String[] args) {
// String() 空构造创建字符串。
String s = new String();
System.out.println(“s:” + s); // 说明重写了toString()方法
System.out.println(“s.length():” + s.length());
System.out.println(“————————”);

    // String(byte[] bytes) 把字节数组转成字符串    byte[] bys = { 97, 98, 99, 100, 101 };    String s2 = new String(bys);    System.out.println("s2:" + s2);    System.out.println("s2.length():" + s2.length());    System.out.println("------------------------");    // String(byte[] bytes, int index, int length) 把字节数组的一部分转成字符串    // StringIndexOutOfBoundsException:索引超出了范围    String s3 = new String(bys, 2, 2);    System.out.println("s3:" + s3);    System.out.println("s3.length():" + s3.length());    System.out.println("------------------------");    // String(char[] value) 把字符数组转成字符串    char[] chs = { 'a', 'b', 'c', 'd', 'e' };    String s4 = new String(chs);    System.out.println("s4:" + s4);    System.out.println("s4.length():" + s4.length());    System.out.println("------------------------");    // String(char[] value, int index, int count) 把字符数组的一部分转成字符串    String s5 = new String(chs, 0, 3);    System.out.println("s5:" + s5);    System.out.println("s5.length():" + s5.length());    System.out.println("------------------------");    // String(String original) 把字符串转成字符串    String s6 = new String("abcde");    System.out.println("s6:" + s6);    System.out.println("s6.length():" + s6.length());    System.out.println("------------------------");    // 直接赋值的方式    String s7 = "abcde";    System.out.println("s7:" + s7);    System.out.println("s7.length():" + s7.length());}

}
显示结果:

s:

s.length():0

s2:abcde

s2.length():5

s3:cd

s3.length():2

s4:abcde

s4.length():5

s5:abc

s5.length():3

s6:abcde

s6.length():5

s7:abcde
s7.length():5

面试题:
A:字符串一旦被赋值就不能被改变。

注意:这里指的是字符串的内容不能发生改变。而字符串的引用是可以再次赋值的。

B:String s = new String(“hello”)和String s = “hello”的区别

前者创建了2个对象
后者创建了1个对象
StringDemo.java

public class StringDemo {
public static void main(String[] args) {
String s = “hello”;
s += “world”;
System.out.println(s); // helloworld

    String s1 = new String("hello");    String s2 = "hello";    System.out.println(s1 == s2); // false    System.out.println(s1.equals(s2)); // true}

}
看程序写结果:

StringDemo2.java

public class StringDemo2 {
public static void main(String[] args) {
// 第一题
String s1 = new String(“hello”);
String s2 = new String(“hello”);
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true

    String s3 = new String("hello");    String s4 = "hello";    System.out.println(s3 == s4); // false    System.out.println(s3.equals(s4));// true    String s5 = "hello";    String s6 = "hello";    System.out.println(s5 == s6);// true    System.out.println(s5.equals(s6));// true    String s7 = "hello";    String s8 = "world";    System.out.println(s7 == s8);// false    System.out.println(s7.equals(s8));// false    // 第二题    String ss1 = "hello";    String ss2 = "world";    String ss3 = "helloworld";    System.out.println(ss3.equals(ss1 + ss2));// true    // 如果是字符串变量相加,先开空间,再相加存储。    // 如果是字符串常量相加,先加,在常量池里面找,如果有就返回常量池里面的地址。否则,就创建新的存储空间。    System.out.println(ss3 == ss1 + ss2);// false    System.out.println(ss3 == "hello" + "world"); // true}

}
常见的方法:

A 判断功能:

public boolean equals(Object anObject)比较字符串的内容是否相同,区分大小写的
public boolean equalsIgnoreCase(String anotherString)比较字符串的内容是否相同,不区分大小写的
public boolean contains(String s)判断字符串中是否包含指定的字符串
public boolean endsWith(String suffix)判断字符串是否以指定的字符串结尾
public boolean startsWith(String prefix)判断字符串是否以指定的字符串开始
public boolean isEmpty()是否为空
StringDemo.java

public class StringDemo {
public static void main(String[] args) {
String s = “helloworld”;

    // public boolean equals(Object anObject):比较字符串的内容是否相同,区分大小写的    System.out.println("equals:" + s.equals("helloworld"));// true    System.out.println("equals:" + s.equals("HelloWorld"));// false    // public boolean equalsIgnoreCase(Object    // anotherString):比较字符串的内容是否相同,不区分大小写的    System.out.println("equalsIgnoreCase:"            + s.equalsIgnoreCase("helloworld"));// true    System.out.println("equalsIgnoreCase:"            + s.equalsIgnoreCase("HelloWorld"));// true    // public boolean contains(String s) 判断字符串中是否包含指定的字符串    System.out.println("contains:" + s.contains("java"));// false    System.out.println("contains:" + s.contains("owo"));// true    // public boolean endsWith(String suffix) 判断字符串是否以指定的字符串结尾    System.out.println("endsWith:" + s.endsWith("java"));// false    System.out.println("endsWith:" + s.endsWith("d"));// true    System.out.println("endsWith:" + s.endsWith("ld"));// true    // public boolean isEmpty()    System.out.println("isEmpty:" + s.isEmpty()); // false    String ss = "";    System.out.println("isEmpty:" + ss.isEmpty()); // true    // NullPointerException    // String sss = null;    // sss.isEmpty();}

}
需求:自己写一个程序,模拟用户登录。

分析:

A:已知用户名和密码。
B:键盘录入用户名和密码。
C:判断。
D:加入多次。给3次机会。
StringTest.java

import java.util.Scanner;
public class StringTest {
public static void main(String[] args) {
// 已知用户名和密码。
String name = “admin”;
String pwd = “admin”;

    for (int x = 0; x < 3; x++) {        // 键盘录入用户名和密码        Scanner sc = new Scanner(System.in);        System.out.println("请输入用户名:");        String username = sc.nextLine();        System.out.println("请输入密码:");        String password = sc.nextLine();        // 判断。        if (name.equals(username) && pwd.equals(password)) {            System.out.println("登录成功");            break;        } else {            System.out.println("登录失败");        }    }}

}
需求:自己写一个程序,模拟用户登录(提升版)。

分析:

A:已知用户名和密码。
B:键盘录入用户名和密码。
C:判断。
D:加入多次。给3次机会。
提示还剩几次机会。
StringTest2.java

import java.util.Scanner;
public class StringTest2 {
public static void main(String[] args) {
// 已知用户名和密码。
String name = “admin”;
String pwd = “admin”;

    // x=0,1,2    for (int x = 0; x < 3; x++) {        // 键盘录入用户名和密码        Scanner sc = new Scanner(System.in);        System.out.println("请输入用户名:");        String username = sc.nextLine();        System.out.println("请输入密码:");        String password = sc.nextLine();        // 判断。        if (name.equals(username) && pwd.equals(password)) {            System.out.println("登录成功,你就可以开始完猜数字小游戏了");            Game.palyGame();            break;        } else {            // 2,1,0            if ((2 - x) == 0) {                System.out.println("帐号被锁定,请与管理员联系");            } else {                System.out.println("登录失败,你还有" + (2 - x) + "次机会");            }        }    }}

}
B 获取功能:

int length():获取字符串的长度
char charAt(int index):获取字符串中指定索引处的字符
int indexOf(int ch):获取ch这个字符在该字符串中第一次出现的索引。
int indexOf(String str):获取str这个字符串在该字符串中第一次出现的索引。
int indexOf(int ch,int fromIndex):获取ch这个字符在该字符串中从指定索引开始后的第一次出现的索引。
int indexOf(String str,int fromIndex):获取str这个字符串在该字符串中从指定索引开始后的第一次出现的索引。
String substring(int start):获取子串。截取。从start到末尾。
String substring(int start,int end):获取子串。截取。从start到end。
StringDemo.java

public class StringDemo {
public static void main(String[] args) {
// 定义一个字符串
String s = “helloworld”;

    // int length():获取字符串的长度    System.out.println("length:" + s.length());    System.out.println("--------------------");    // char charAt(int index):获取字符串中指定索引处的字符    System.out.println("charAt:" + s.charAt(2));// l    System.out.println("charAt:" + s.charAt(5));// w    System.out.println("--------------------");    // int indexOf(int ch):获取ch这个字符在该字符串中第一次出现的索引。    System.out.println("indexOf:" + s.indexOf('o'));    // System.out.println("indexOf:" + s.indexOf('a')); // -1    // int indexOf(int ch,int fromIndex):获取ch这个字符在该字符串中从指定索引开始后的第一次出现的索引。    System.out.println("indexOf:" + s.indexOf('o', 5));    System.out.println("--------------------");    // String substring(int start):获取子串。截取。从start到末尾。    System.out.println("substring:" + s.substring(5)); // world    // String substring(int start,int end):获取子串。截取。从start到end。    System.out.println("substring:" + s.substring(5, 8)); // wor}

}
a.遍历字符串。依次获取字符串中的每一个字符。

通过length()方法和charAt()方法结合可以实现字符串的遍历。
StringTest.java

public class StringTest {
public static void main(String[] args) {
// 定义一个字符串
String s = “helloworld”;

    // charAt(int index);    // System.out.println(s.charAt(0));    // System.out.println(s.charAt(1));    // System.out.println(s.charAt(2));    // System.out.println(s.charAt(3));    // System.out.println(s.charAt(4));    // ...    for (int x = 0; x < s.length(); x++) {        System.out.println(s.charAt(x));    }}

}
b.需求:键盘录入一个字符串:假如该字符串只有数字,英文字符串组成。请分别统计数字,大写字母,小写字母各有多少个?

举例:

"Hello123World"

结果:

大写:2个小写:8个数字:3个

分析:

A:键盘录入一个字符串。
B:定义三个统计变量。
C:遍历字符串获取到每一个字符。
D:判断它是什么:

任意一个字符:x大写:小写:数字:  方式1:x>=48 && x<=57  方式2:x>='0' && x<='9'对应的统计变量++。

E:输出即可。
StringTest2.java

public class StringTest2 {
public static void main(String[] args) {
// 键盘录入一个字符串。
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个字符串:”);
String line = sc.nextLine();

    // 定义三个统计变量。    int bigCount = 0;    int smallCount = 0;    int numberCount = 0;    // 遍历字符串获取到每一个字符。    for (int x = 0; x < line.length(); x++) {        char ch = line.charAt(x);        if (ch >= '0' && ch <= '9') {            numberCount++;        } else if (ch >= 'a' && ch <= 'z') {            smallCount++;          } else{            bigCount++;        }    }    //输出即可。    System.out.println("大写:"+bigCount);    System.out.println("小写:"+smallCount);    System.out.println("数字:"+numberCount);}

}

C 转换功能:

byte[] getBytes():把字符串转成字节数组。
char[] toCharArray():把字符串转成字符数组。
static String copyValueOf(char[] chs):把字符数组转成字符串。
static String valueOf(char[] chs):把字符数组转成字符串。
static String valueOf(int i)基本类型:把int类型的数据转成字符串。
String toLowerCase():字符串转成小写
String toUpperCase():字符串转成大写
String concat(String str):字符串的拼接

public class StringDemo {
public static void main(String[] args) {
String s = “abcde”;

    // byte[] getBytes():把字符串转成字节数组。    byte[] bys = s.getBytes();    for (int x = 0; x < bys.length; x++) {        System.out.println(bys[x]);    }    System.out.println("----------------");    // char[] toCharArray():把字符串转成字符数组。    char[] chs = s.toCharArray();    for (int x = 0; x < chs.length; x++) {        System.out.println(chs[x]);    }    System.out.println("----------------");    // static String copyValueOf(char[] chs):把字符数组转成字符串。    String s2 = String.copyValueOf(chs);    System.out.println(s2);    System.out.println("----------------");    // static String valueOf(char[] chs):把字符数组转成字符串。    String s3 = String.valueOf(chs);    System.out.println(s3);    System.out.println("----------------");    // static String valueOf(int i)基本类型:把int类型的数据转成字符串。    int i = 100;    String s4 = String.valueOf(i);    System.out.println(s4);    System.out.println("----------------");    // String toLowerCase():字符串转成小写    System.out.println(s.toLowerCase());    System.out.println("----------------");    // String toUpperCase():字符串转成大写    System.out.println(s.toUpperCase());    System.out.println("----------------");    // String concat(String str):字符串的拼接    String s5 = "abc";    String s6 = "de";    String s7 = s5 + s6;    String s8 = s5.concat(s6);    System.out.println(s7);    System.out.println(s8);}

}
需求:键盘录入一个任意字符串。由英文组成。把该字符串的首字母转成大写,其他全部小写。

举例:

hellowWASFDA
结果:

Hellowwasfda
分析:

A:键盘录入字符串。
B:截取字符串得到第一个字符的字符串。
C:截取字符串得到除了第一个以后的字符串。
D:把B大写+C小写。
StringTest.java

import java.util.Scanner;
public class StringTest {
public static void main(String[] args) {
// 键盘录入字符串。
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个字符串:”);
String line = sc.nextLine();

    // 截取字符串得到第一个字符的字符串。    String s1 = line.substring(0, 1);    // 截取字符串得到除了第一个以后的字符串。    String s2 = line.substring(1);    // 把B大写+C小写。    String s3 = s1.toUpperCase() + s2.toLowerCase();    System.out.println(s3);    // 再来一个 链式编程    // String result = line.substring(0, 1).toUpperCase()    // .concat(line.substring(1).toLowerCase());    // System.out.println(result);}

}
D 其他功能:

替换功能

String replace(char old,char new):用new字符替代old字符。
String replace(String old,String new):用new字符串替代old字符串。

public class StringDemo {
public static void main(String[] args) {
String s = “helloworld”;
String s2 = s.replace(‘l’, ‘k’);
System.out.println(s);
System.out.println(s2);
}
}
去除字符串两空格String trim()

按字典顺序比较两个字符串

int compareTo(String str)
int compareToIgnoreCase(String str)
返回值:

正数:说明调用者大
0:说明字符串相同
负数:说明调用者小

public class StringDemo3 {
public static void main(String[] args) {
String s = “java”;

    String s2 = "abcde";    String s3 = "Java";    String s4 = "world";    // System.out.println('j' - 'a');    // System.out.println('j' - 'w');    System.out.println(s.compareTo(s2));// 9    System.out.println(s.compareToIgnoreCase(s3));// 0    System.out.println(s.compareTo(s4));// -13}

}
需求:查找大串中小串出现的次数。

分析:

A:定义两个字符串。
B:写一个功能实现。

a:定义一个统计变量
b:查找小串在大串中第一次出现的索引
c:看返回值是否是-1

是:说明不存在了,返回统计变量。
否:说明存在,统计变量++。
d:把查找过的部分截取掉,作为新的大串。

e:重复b的动作。
C:调用功能,输出结果。

public class StringTest {
public static void main(String[] args) {
// 定义两个字符串
String maxString = “helloakworakldhahakjavaxixihaakha”;
String minString = “ak”;

    // 写一个功能实现。    int count = getCount(maxString, minString);    System.out.println(count);}/* * 返回值:int 参数列表:String s,String ss */public static int getCount(String maxString, String minString) {    int count = 0;    int index = maxString.indexOf(minString);    while (index != -1) {        count++;        maxString = maxString.substring(index + minString.length());        index = maxString.indexOf(minString);    }    return count;}

}
java中的参数传递问题

形式参数:

基本类型:形式参数的改变对实际参数没有影响。
引用类型:形式参数的改变对实际参数有影响。
类,接口,数组。
String – 类 – 引用类型。

字符串是一种特殊的引用类型。可以把它当作基本类型的值来看。
ArgsDemo.java

public class ArgsDemo {
public static void main(String[] args) {
int a = 10;
int b = 20;
change(a, b);
System.out.println(a + “—” + b); // 10—20

    int[] arr = { 1, 2, 3, 4, 5 };    change(arr);    for (int x = 0; x < arr.length; x++) {        System.out.println(arr[x]);// 2,4,6,8,10    }    String s1 = "hello";    String s2 = "world";    change(s1, s2);    System.out.println(s1 + "---" + s2);// hello---world}public static void change(String s1, String s2) {    s1 = "haha";    s2 = "hehe";}public static void change(int[] arr) {    for (int x = 0; x < arr.length; x++) {        arr[x] *= 2;    }}public static void change(int a, int b) {    a = b;    b = a + b;}

}
StringBuffer类

字符串缓冲类

public final class StringBuffer extends Object implements Serializable, CharSequence

线程安全的可变字符序列。

和String类的区别?
A:String的字符串内容是不可以改变的。
B:StringBuffer的字符串内容是可以改变的。
构造方法:

A:StringBuffer() 构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。
B:StringBuffer(int capacity) 构造一个不带字符,但具有指定初始容量的字符串缓冲区。
C:StringBuffer(String str) 构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。
实际值:public int length()
返回长度(字符数)。
理论值:public int capacity()
返回当前容量。容量指可用于最新插入的字符的存储量,超过这一容量就需要再次进行分配。
1.StringBufferDemo.java

public class StringBufferDemo {
public static void main(String[] args) {
// 方式1
StringBuffer sb = new StringBuffer();
System.out.println(“sb:” + sb);
System.out.println(“sb.length():” + sb.length());//0
System.out.println(“sb.capacity():” + sb.capacity());//16
System.out.println(“——————————”);

    // 方式2    StringBuffer sb2 = new StringBuffer(50);    System.out.println("sb2:" + sb2);    System.out.println("sb2.length():" + sb2.length());//0    System.out.println("sb2.capacity():" + sb2.capacity());//50    System.out.println("------------------------------");    // 方式3    StringBuffer sb3 = new StringBuffer("helloworld");    System.out.println("sb3:" + sb3);//helloworld    System.out.println("sb3.length():" + sb3.length());//10    System.out.println("sb3.capacity():" + sb3.capacity());//26}

}
常见方法

添加功能:

public StringBuffer append(String str):把任意类型的数据添加到StringBuffer中。
public StringBuffer insert(int offset,String str):把任意类型的数据插入到StringBuffer指定位置中。
注意:StringBuffer操作后,如果返回StringBuffer类型, 其实返回的是本身对象。

Demo

public class StringBufferDemo {
public static void main(String[] args) {
// 创建缓冲区对象
StringBuffer sb = new StringBuffer();
StringBuffer sb2 = sb.append(“hello”);
System.out.println(sb);
System.out.println(sb2);
System.out.println(sb == sb2);

    // sb.append("hello");    // sb.append(true);    // sb.append(10);    // sb.append(12.456);    // 链式编程    sb.append("hello").append(true).append(10).append(12.456);    // 插入    sb.insert(5, "java");    System.out.println(sb);}

}
显示的结果

hello
hello
true
hellojavahellotrue1012.456
删除功能:

public StringBuffer delete(int start,int end):删除从start开始,到end结束的数据。
public StringBuffer deleteCharAt(int index):删除index位置的字符。

public class StringBufferDemo {
public static void main(String[] args) {
// 创建对象
StringBuffer sb = new StringBuffer();
sb.append(“hello”).append(“world”).append(“java”);

    // 需求:我要删除掉world这个内容    sb.delete(5, 10);    System.out.println(sb);//hellojava    // 需求:我要删除w    //sb.deleteCharAt(5);    System.out.println(sb);//helloorldjava    //需求:我要删除world    sb.deleteCharAt(5);    sb.deleteCharAt(5);    sb.deleteCharAt(5);    sb.deleteCharAt(5);    sb.deleteCharAt(5);    System.out.println(sb);//hellojava}

}
替换功能:

public StringBuffer replace(int start,int end,String str)

public class StringBufferDemo {
public static void main(String[] args) {
// 创建对象
StringBuffer sb = new StringBuffer();

    sb.append("hello");    sb.append("world");    sb.append("java");    // 需求:我要把world替换为ak47    sb.replace(5, 10, "ak47");    System.out.println(sb);}

}
截取功能:

public String substring(int start)
public String substring(int start,int end)

public class StringBufferDemo {
public static void main(String[] args) {
// 创建对象
StringBuffer sb = new StringBuffer();

    sb.append("hello");    sb.append("world");    sb.append("java");    // public String substring(int start)    String s = sb.substring(5);    System.out.println(s);//worldjava    System.out.println(sb);//helloworldjava}

}
1.把数组转成字符串:

数组int[] arr = {11,22,33,44,55},写一个功能,把数组中的数据返回成如下的字符串:”[11, 22, 33, 44, 55]”

分析:

A:定义一个数组。
B:写功能
形式参数:数组
返回值类型:字符串

遍历数组,拼接字符串。

C:调用功能
StringTest.java

public class StringTest {
public static void main(String[] args) {
// 定义一个数组。
int[] arr = { 11, 22, 33, 44, 55 };

    // 功能    String s = arrayToString(arr);    //输出结果    System.out.println(s);}public static String arrayToString(int[] arr) {    String s = "";    s += "[";    for (int x = 0; x < arr.length; x++) {        if (x == arr.length - 1) {            s += arr[x];        } else {            s += arr[x] + ", ";        }    }    s += "]";    return s;}

}
2.把字符串反转

键盘录入一个字符串:”abc”,请写一个功能实现返回一个字符串:”cba”

分析:

A:键盘录入一个字符串
B:写功能
形式参数:字符串
返回值类型:字符串

倒着输出。   倒着拼接。

C:调用,输出结果
StringTest2.java

import java.util.Scanner;
public class StringTest2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个字符串:”);
String line = sc.nextLine();

    String s = myReverse(line);    System.out.println(s);}// 功能public static String myReverse(String str) {    String result = "";    char[] chs = str.toCharArray();    for (int x = chs.length - 1; x >= 0; x--) {        result += chs[x];    }    return result;}

}
3.String和StringBuffer的相互转换

String – StringBuffer
StringBuffer sb = new StringBuffer(s);
StringBuffer – String

String s = new String(sb);
StringBufferDemo.java

public class StringBufferDemo {
public static void main(String[] args) {
// String s = “helloworld”;
// StringBuffer sb = s;

    // StringBuffer sb = new StringBuffer();    // String ss = sb;    // String -- StringBuffer    String s = "hello";    // 方式1    StringBuffer sb = new StringBuffer(s);    // 方式2    StringBuffer sb2 = new StringBuffer();    sb2.append(s);    StringBuffer sb3 = new StringBuffer("haha");    // 方式1    String ss = new String(sb3);    // 方式2    String sss = sb3.toString();}

}
4.StringBuffer改进字符串的拼接

(1) public StringBuffer reverse()

public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append(“abc”);
sb.reverse();
System.out.println(sb);
}
}
(2) 一个数组:int[] arr = {11,22,33,44,55},请写一个功能,把数组中的数据返回成如下的字符串:”[11, 22, 33, 44, 55]”

分析:

A:定义一个数组。
B:写功能
形式参数:数组
返回值类型:字符串
遍历数组,拼接字符串。
C:调用功能
改进的代码

public class StringBufferDemo {
public static void main(String[] args) {
// 定义一个数组。
int[] arr = { 11, 22, 33, 44, 55 };

    // 功能    String s = arrayToString(arr);    // 输出结果    System.out.println(s);}public static String arrayToString(int[] arr) {    StringBuffer sb = new StringBuffer();    sb.append("[");    for (int x = 0; x < arr.length; x++) {        if (x == arr.length - 1) {            sb.append(arr[x]);        } else {            sb.append(arr[x]).append(", ");        }    }    sb.append("]");    return sb.toString();}

}
(3) 键盘录入一个字符串:”abc”,请写一个功能实现返回一个字符串:”cba”

分析:

A:键盘录入一个字符串
B:写功能
形式参数:字符串
返回值类型:字符串
倒着输出。 倒着拼接。
C:调用,输出结果
改进的代码

public class StringBufferDemo2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个字符串:”);
String line = sc.nextLine();

    String s = myReverse(line);    System.out.println(s);}// 功能public static String myReverse(String str) {    // StringBuffer sb = new StringBuffer(str);    // sb.reverse();    // return sb.toString();    return new StringBuffer(str).reverse().toString();}

}
(4) (面试题)String,StringBuffer,StringBuilder的区别?

String:字符长度是固定的。
StirngBuffer/StringBuilder:字符长度可变的。
StringBuffer:安全的,效率低。
StringBuilder:不安全的,效率高。
StringBuffer和StringBuilder的兼容。
数组排序:(冒泡,选择)

冒泡:相邻比较。

public class ArrayDemo {
public static void main(String[] args) {
// 定义一个数组:
int[] arr = { 24, 69, 80, 57, 13 };

    System.out.println("排序前:");    printArray(arr);    // 第一次排序:    // for (int x = 0; x < arr.length - 1 - 0; x++) {    // if (arr[x] > arr[x + 1]) {    // int temp = arr[x];    // arr[x] = arr[x + 1];    // arr[x + 1] = temp;    // }    // }    // System.out.println("第一次完毕:");    // printArray(arr);    //    // 第二次排序:    // for (int x = 0; x < arr.length - 1 - 1; x++) {    // if (arr[x] > arr[x + 1]) {    // int temp = arr[x];    // arr[x] = arr[x + 1];    // arr[x + 1] = temp;    // }    // }    // System.out.println("第二次完毕:");    // printArray(arr);    //    // 第三次排序:    // for (int x = 0; x < arr.length - 1 - 1 - 1; x++) {    // if (arr[x] > arr[x + 1]) {    // int temp = arr[x];    // arr[x] = arr[x + 1];    // arr[x + 1] = temp;    // }    // }    // System.out.println("第三次完毕:");    // printArray(arr);    //    // 第四次排序:    // for (int x = 0; x < arr.length - 1 - 1 - 1 - 1; x++) {    // if (arr[x] > arr[x + 1]) {    // int temp = arr[x];    // arr[x] = arr[x + 1];    // arr[x + 1] = temp;    // }    // }    // System.out.println("第四次完毕:");    // printArray(arr);    for (int y = 0; y < arr.length - 1; y++) {        for (int x = 0; x < arr.length - 1 - y; x++) {            if (arr[x] > arr[x + 1]) {                int temp = arr[x];                arr[x] = arr[x + 1];                arr[x + 1] = temp;            }        }    }    System.out.println("排序后:");    System.out.println("第四次完毕:");    printArray(arr);}public static void printArray(int[] arr) {    System.out.print("[");    for (int x = 0; x < arr.length; x++) {        if (x == arr.length - 1) {            System.out.print(arr[x]);        } else {            System.out.print(arr[x] + ", ");        }    }    System.out.println("]");}

}
选择:从0和后面的比较。

public class ArrayDemo {
public static void main(String[] args) {
// 定义一个数组:
int[] arr = { 24, 69, 80, 57, 13 };

    System.out.println("排序前:");    printArray(arr);    // // 第一次    // int x = 0;    // for (int y = x + 1; y < arr.length; y++) {    // if (arr[y] < arr[x]) {    // int temp = arr[x];    // arr[x] = arr[y];    // arr[y] = temp;    // }    // }    // System.out.println("第一次完毕:");    // printArray(arr);    //    // // 第二次    // x = 1;    // for (int y = x + 1; y < arr.length; y++) {    // if (arr[y] < arr[x]) {    // int temp = arr[x];    // arr[x] = arr[y];    // arr[y] = temp;    // }    // }    // System.out.println("第二次完毕:");    // printArray(arr);    //    // // 第三次    // x = 2;    // for (int y = x + 1; y < arr.length; y++) {    // if (arr[y] < arr[x]) {    // int temp = arr[x];    // arr[x] = arr[y];    // arr[y] = temp;    // }    // }    // System.out.println("第三次完毕:");    // printArray(arr);    //    // // 第四次    // x = 3;    // for (int y = x + 1; y < arr.length; y++) {    // if (arr[y] < arr[x]) {    // int temp = arr[x];    // arr[x] = arr[y];    // arr[y] = temp;    // }    // }    // System.out.println("第四次完毕:");    // printArray(arr);    for (int x = 0; x < arr.length - 1; x++) {        for (int y = x + 1; y < arr.length; y++) {            if (arr[y] < arr[x]) {                int temp = arr[x];                arr[x] = arr[y];                arr[y] = temp;            }        }    }    System.out.println("排序后:");    printArray(arr);}public static void printArray(int[] arr) {    System.out.print("[");    for (int x = 0; x < arr.length; x++) {        if (x == arr.length - 1) {            System.out.print(arr[x]);        } else {            System.out.print(arr[x] + ", ");        }    }    System.out.println("]");}

}
数组查找:

A:基本查找(从头开始找,找到就结束,并返回该处的索引。如果找不到返回-1)
B:折半查找,二分查找。
前提:数组有序。
ArrayDemo.java

public class ArrayDemo {
public static void main(String[] args) {
// 定义数组
int[] arr = { 11, 22, 33, 44, 55, 66, 77, 88, 99 };

    // 功能    int index = getIndex(arr, 88);    System.out.println(index);    index = getIndex(arr, 22);    System.out.println(index);    index = getIndex(arr, 250);    System.out.println(index);}/* * 返回值类型:int 参数列表:数组,被查找的元素 */public static int getIndex(int[] arr, int value) {    // 定义索引    int max = arr.length - 1;    int min = 0;    int mid = (max + min) / 2;    // 先判断一次    while (arr[mid] != value) {        if (arr[mid] > value) {            max = mid - 1;        } else if (arr[mid] < value) {            min = mid + 1;        }        // 记得判断一次min要小于max        if (min > max) {            return -1;        }        // 重新计算mid        mid = (min + max) / 2;    }    return mid;}

}
Arrays工具类的使用

Arrays:针对数组进行操作的工具类。成员方法都是静态的。通过类名调用。

方法:
A:把数组转成字符串
public static String toString(int[] a) 把数组转成字符串。
B:排序(底层快速排序)
public static void sort(int[] a) 把数组排序
C:查找
public static int binarySearch(int[] a,int key)
ArraysDemo.java

public class ArraysDemo {
public static void main(String[] args) {
// 定义数组
int[] arr = { 22, 11, 44, 33, 55 };

    // public static String toString(int[] a) 把数组转成字符串。    System.out.println(Arrays.toString(arr));    // public static void sort(int[] a) 把数组排序    Arrays.sort(arr);    System.out.println(Arrays.toString(arr));    // 11,22,33,44,55    // public static int binarySearch(int[] a,int key)    int index = Arrays.binarySearch(arr, 22);    System.out.println(index);    index = Arrays.binarySearch(arr, 44);    System.out.println(index);    index = Arrays.binarySearch(arr, 144);    System.out.println(index);}

}
把字符串之间的字符排序

需求:有一个字符串:”dafcebg”。请想办法,把这个字符串变成:”abcdefg”

分析:

A:定义一个字符串。”dafcebg”。
B:把字符串转换成字符数组。
C:把字符数组进行排序。
D:把排序后的字符数组转成字符串。
ArraysDemo.java

public class ArrayDemo {
public static void main(String[] args) {
// 定义一个字符串。”dafcebg”。
String s = “dafcebg”;

    // 把字符串转换成字符数组。    char[] chs = s.toCharArray();    // 把字符数组进行排序。    Arrays.sort(chs);    // 把排序后的字符数组转成字符串。    // 这个可以,但是不满足要求:元素, 元素, ...    // String result = Arrays.toString(chs);    // System.out.println(result);    // String ss = new String(chs);    // String ss = String.copyValueOf(chs);    String ss = String.valueOf(chs);    System.out.println(ss);}

}
Integer类

public final class Integerextends Number implements Comparable
Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。

需求1:给出一个数据,请判断是否在int范围呢?

int范围的最大值,最小值。
需求2:给出一个int类型的值,请写出:

60
二进制:111100
八进制:74
十六进制的表示形式:3c
基本类型的值是没有方法可以调用的。但是,很多操作的可能比较复杂,这个时候,java就提供了一种方式:包装的方式。

把所有的基本类型都给包装成一个对象的类类型。

byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
IntegerDemo.java

public class IntegerDemo {
public static void main(String[] args) {
// Integer

    // public static final int MAX_VALUE    // public static final int MIN_VALUE    System.out.println(Integer.MAX_VALUE);    System.out.println(Integer.MIN_VALUE);    // public static String toBinaryString(int i)    // public static String toOctalString(int i)    // public static String toHexString(int i)    System.out.println(Integer.toBinaryString(60));    System.out.println(Integer.toOctalString(60));    System.out.println(Integer.toHexString(60));}

}

构造方法:

Integer(int num)
Integer(String str)
注意:这里的字符串必须是数字类型的。
IntegerDemo.java

public class IntegerDemo {
public static void main(String[] args) {
// 方式1
int num = 100;
Integer i = new Integer(num);
System.out.println(i);
System.out.println(i.toString());

    // 方式2    // String str = "100";    // String str = "001";    String str = "100abc";    // NumberFormatException    Integer ii = new Integer(str);    System.out.println(ii);}

}
String类型和Integer类型的相互转换

int – String
+” “
String.valueOf(num)
String – int
Integer.parseInt(s)
IntegerDemo.java

public class IntegerDemo {
public static void main(String[] args) {
// int–String
int num = 100;
// 方式1
String s1 = num + “”;
// 方式2
String s2 = String.valueOf(num);
// 方式3
// int – Integer –String
Integer i = new Integer(num);
String s3 = i.toString();
// 方式4
// public static String toString(int i)
String s4 = Integer.toString(num);

    // String --int    String s = "100";    // 方式1    // String -- Integer -- int    Integer ii = new Integer(s);    // public int intValue()    int number = ii.intValue();    System.out.println(number);    // 方式2    //public static int parseInt(String s)    int number2 = Integer.parseInt(s);}

}
十进制到其他进制的转换:
public static String toString(int i,int radix)
其他进制到十进制的转换:
public static int parseInt(String s,int radix)
IntegerDemo.java

public class IntegerDemo {
public static void main(String[] args) {
// 十进制到其他进制
System.out.println(Integer.toString(100, 2));
System.out.println(Integer.toString(100, 8));
System.out.println(Integer.toString(100, 16));
System.out.println(Integer.toString(100, 7));
System.out.println(Integer.toString(100, 9));
// 进制难道是没有范围的吗? 2-36
System.out.println(Integer.toString(100, -2));
System.out.println(Integer.toString(100, 1));
System.out.println(Integer.toString(100, 17));
System.out.println(Integer.toString(100, 100));
System.out.println(Integer.toString(100, 36));
System.out.println(Integer.toString(100, 37));
System.out.println(“———————–”);

    // 其他进制到十进制    System.out.println(Integer.parseInt("100", 10));    System.out.println(Integer.parseInt("100"));    System.out.println(Integer.parseInt("100", 2));    System.out.println(Integer.parseInt("100", 8));    System.out.println(Integer.parseInt("100", 16));    System.out.println(Integer.parseInt("100", 22));}

}
JDK5的新特性:

自动装箱:基本类型–引用类型
Integer.valueOf(100);
自动拆箱:引用类型–基本类型
i.intValue();
IntegerDemo.java

public class IntegerDemo {
public static void main(String[] args) {
// Integer i = new Integer(100);
Integer i = 100; // 自动装箱
// Integer.valueOf(100);
i += 200; // 自动拆箱,自动装箱
// i = Integer.valueOf(i.intValue() + 200);
System.out.println(i);
}
}
byte常量池的面试题。

public class IntegerDemo {
public static void main(String[] args) {
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2);// false
System.out.println(i1.equals(i2));// true

    Integer i3 = new Integer(128);    Integer i4 = new Integer(128);    System.out.println(i3 == i4);// false    System.out.println(i3.equals(i4));// true    Integer i5 = 127;    Integer i6 = 127;    System.out.println(i5 == i6);// true    System.out.println(i5.equals(i6));// true    Integer i7 = 128;    Integer i8 = 128;    System.out.println(i7 == i8);// false    System.out.println(i7.equals(i8));// true}

}
正则表达式

正则表达式:符合一定规则的字符串。

题目:校验QQ号码。

要求:
1 长度是6-12位。
2 不能以0开头。
3 全部是数字组成。
分析:
A:键盘录入QQ号码。
B:写一个功能校验
返回值类型:boolean
参数列表:String qq
长度是6-12位:字符串的长度。
不能以0开头:判断是否以指定的字符串开头
全部是数字组成:遍历得到每一个字符,判断是否有不满足,有就失败。
C:调用功能即可。
RegexDemo.java

public class RegexDemo {
public static void main(String[] args) {
// 创建对象
Scanner sc = new Scanner(System.in);
System.out.println(“请输入QQ号码:”);
String qq = sc.nextLine();
boolean flag = checkQQ(qq);
System.out.println(flag);
// 使用正则表达式
boolean flag2 = checkQQ2(qq);
System.out.println(flag2);
}

public static boolean checkQQ2(String qq) {    // String regex = "[1-9][0-9]{5,11}";    // boolean flag = qq.matches(regex);    // return flag;    return qq.matches("[1-9][0-9]{5,11}");}public static boolean checkQQ(String qq) {    boolean flag = true;    // 长度    if (qq.length() >= 6 && qq.length() <= 12) {        // 不能以0开头        if (!qq.startsWith("0")) {            // 全部是数字组成            char[] chs = qq.toCharArray();            for (int x = 0; x < chs.length; x++) {                char ch = chs[x];                if (!(ch >= '0' && ch <= '9')) {                    flag = false;                    break;                }            }        } else {            flag = false;        }    } else {        flag = false;    }    return flag;}

}
正则表达式的组成规则(java.util.regex 类 Pattern)

1:字符
x 字符 x
\ 反斜线字符
\r 回车
\n 换行

2:字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内
[0-9] 0-9的数字字符

3:预定义字符类
. 任何字符
\d 数字:[0-9]
\w 单词字符:[a-zA-Z_0-9]
在正则表达式中可以组成单词的字符。

4:边界匹配器
^ 行的开头
$ 行的结尾
\b 单词边界 (出现的地方不能是单词字符。)
hello,world ja?v;a

helloworldjava

5:数量词
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次9

正则表达式的判断功能:

public boolean matches(String regex):判断字符串对象是否匹配给定的正则表达式。
校验电话号码 写一个规则

import java.util.Scanner;
public class RegexDemo {
public static void main(String[] args) {
// 校验电话号码
// 写一个规则
/*
* 13245678901 13345674567 13436975980 18812345678 18611113456
* 18598988989 18888888888
*/

    //如何写出规则    String regex = "1[38][0-9]{9}";    Scanner sc = new Scanner(System.in);    System.out.println("请输入电话号码:");    String phone = sc.nextLine();    boolean flag = phone.matches(regex);    System.out.println(flag);}

}
正则表达式的练习(邮箱)

需求:校验Email。邮箱。

public class RegexTest {
public static void main(String[] args) {
/*
* charlie@163.com linqingxia@126.com liuxiaoqu@yahoo.cn haha@sina.com.cn
* …
*/
// String regex = “[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\.[a-zA-Z]{2,3})+”;
String regex = “\w+@\w{2,6}(\.\w{2,3})+”;

    Scanner sc = new Scanner(System.in);    System.out.println("请输入邮箱:");    String email = sc.nextLine();    boolean flag = email.matches(regex);    System.out.println(flag);}

}
正则表达式的分割功能

public String[] split(String regex)

public class RegexDemo {
public static void main(String[] args) {
// 年龄范围
String ages = “28-35”; // 字符串对象

    String regex = "-"; // 规则对象    // 调用方法    String[] ageArray = ages.split(regex);    for (int x = 0; x < ageArray.length; x++) {        System.out.println(ageArray[x]);    }    int startAge = Integer.parseInt(ageArray[0]);    int endAge = Integer.parseInt(ageArray[1]);}

}
正则表达式的分割功能练习

public class RegexDemo2 {
public static void main(String[] args) {
// 案例1:”aa,bb,cc”
String str = “aa,bb,cc”;
String regex = “,”;
String[] strArray = str.split(regex);
for (int x = 0; x < strArray.length; x++) {
System.out.println(strArray[x]);
}
System.out.println(“——————–”);
// 案例2:”aa.bb.cc”
String str2 = “aa.bb.cc”;
String regex2 = “\.”;
String[] strArray2 = str2.split(regex2);
for (int x = 0; x < strArray2.length; x++) {
System.out.println(strArray2[x]);
}
System.out.println(“——————–”);
// 案例3:”aa bb cc”
String str3 = “aa bb cc”;
String regex3 = ” “;
String[] strArray3 = str3.split(regex3);
for (int x = 0; x < strArray3.length; x++) {
System.out.println(strArray3[x]);
}
System.out.println(“——————–”);
// 案例4:”aa bb cc”
String str4 = “aa bb cc”;
String regex4 = ” +”;
String[] strArray4 = str4.split(regex4);
for (int x = 0; x < strArray4.length; x++) {
System.out.println(strArray4[x]);
}
System.out.println(“——————–”);
// 案例5:”D:\itcast\20140725\day14\resource”
String str5 = “D:\itcast\20140725\day14\resource”;
String regex5 = “\\”;
String[] strArray5 = str5.split(regex5);
for (int x = 0; x < strArray5.length; x++) {
System.out.println(strArray5[x]);
}
}
}
把字符串中的数字进行排序

一个字符串:”45 98 27 36 10”。请想办法,最终输出一个字符串:”10 27 36 45 98”

分析:
A:定义一个字符串。
B:分割字符串得到一个字符串数组。
C:把字符串数组转换为int数组。
D:对int数组进行排序。
E:把排序后的数组元素拼接的到一个字符串。
RegexTest.java

public class RegexTest {
public static void main(String[] args) {
// 定义一个字符串。
String s = “45 98 27 36 10”;

    // 分割字符串得到一个字符串数组。    String[] strArray = s.split(" ");    // 定义int数组    int[] arr = new int[strArray.length];    // 把字符串数组转换为int数组。    // 错误    // arr = Integer.parseInt(strArray);    // arr[0] = Integer.parseInt(strArray[0]);    // arr[1] = Integer.parseInt(strArray[1]);    // arr[2] = Integer.parseInt(strArray[2]);    // ...    for (int x = 0; x < arr.length; x++) {        arr[x] = Integer.parseInt(strArray[x]);    }    // 对int数组进行排序。    Arrays.sort(arr);    // 把排序后的数组元素拼接的到一个字符串。    StringBuilder sb = new StringBuilder();    for (int x = 0; x < arr.length; x++) {        if (x == arr.length - 1) {            sb.append(arr[x]);        } else {            sb.append(arr[x]).append(" ");        }    }    String result = sb.toString();    System.out.println(result);}

}
正则表达式的替换功能

public String replaceAll(String regex,String replacement)

public class RegexDemo {
public static void main(String[] args) {
String str = “haha123xixi456heh789java”;

    // 需求:把数字替换成*号    // String regex = "\\d+";    String regex = "\\d";    String result = str.replaceAll(regex, "*");    System.out.println(result);}

}
正则表达式的获取功能

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
* 获取功能:
* Pattern和Matcher类。
*/
public class RegexDemo {
public static void main(String[] args) {
// 典型的调用顺序是

    // // 把正则表达式字符串通过compile方法编译生成模式对象。    // Pattern p = Pattern.compile("a*b");    // // 通过模式对象调用matcher方法,参数是被操作的字符串。返回一个匹配器对象。    // Matcher m = p.matcher("aaaaab");    // // 用匹配器进行匹配    // boolean b = m.matches();    // System.out.println(b);    //    // String str = "aaaaab";    // String regex = "a*b";    // boolean flag = str.matches(regex);    // System.out.println(flag);    // 获取功能:请把这个字符串中的三个字符组成的单词给找出来。    // 需求:"zhu yi le, ming tian bu fang jia,thank you"    String str = "zhu yi le, ming tian bu fang jia,thank you";    String regex = "\\b[a-z]{3}\\b";    Pattern p = Pattern.compile(regex);    Matcher m = p.matcher(str);    // 注意:获取之前,一定要先判断是否存在满足条件的数据。    // 第一次    // public boolean find()    // boolean flag = m.find();    // System.out.println(flag);    //    // // public String group()    // String s = m.group();    // System.out.println(s);    //    // // 第二次    // flag = m.find();    // System.out.println(flag);    // s = m.group();    // System.out.println(s);    //    // // 第三次    // flag = m.find();    // System.out.println(flag);    // s = m.group();    // System.out.println(s);    while(m.find()){        System.out.println(m.group());    }}

}
Random类

Random:用于产生随机数的类。

public class Random extends Object implements Serializable
实现Serializable序列化接口
子类SecureRandom
Random类的构造方法:

Random():没有种子。默认种子,当前时间的毫秒值。
Random(long seed):有种子。指定的种子,种子相同,产生的随机数也相同。
Random类的成员方法:

public int nextInt():int范围内的数据
public int nextInt(int n):[0,n)的范围数据

import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
// 方式1
// Random r = new Random();

    // 方式2    Random r = new Random(17);    // int范围的    // for (int x = 0; x < 10; x++) {    // System.out.println(r.nextInt());    // }    // [0,n)的范围    for (int x = 0; x < 10; x++) {        System.out.println(r.nextInt(100));    }}

}

随机产生人的姓名。

分析:

A:定义一个字符串数组中存储大家的名称。
B:随机产生一个在数组长度范围内的索引值。
C:通过数组名称配合B产生的索引,就能获取这个值。

import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
// 定义一个字符串数组中存储大家的名称。
String[] strArray = { “林青霞”, “汪精卫”, “蒋介石”, “毛泽东”, “朱德” };

    // 随机产生一个在数组长度范围内的索引值。    Random r = new Random();    int index = r.nextInt(strArray.length);    // 通过数组名称配合B产生的索引,就能获取这个值。    System.out.println(strArray[index]);}

}
System类

System:没有构造方法,成员全部是静态的。

public final class System extends Object

public static void gc():运行垃圾回收器。
public static void exit(int status):终止当前正在运行的 Java 虚拟机。根据惯例,非 0 的状态码表示异常终止。
public static long currentTimeMillis():返回以毫秒为单位的当前时间。

public class SystemDemo {
public static void main(String[] args) {
// System.out.println(“hello”);
// System.exit(0);
// System.out.println(“world”);

    // long time = System.currentTimeMillis();    // System.out.println(time);    long start = System.currentTimeMillis();    for (int x = 0; x < 1000000; x++) {        System.out.println(x);    }    long end = System.currentTimeMillis();    System.out.println("end-start:" + (end - start) + "毫秒");}

}
System类复制数组的方法

public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目标数据中的起始位置。
length - 要复制的数组元素的数量。

public class SystemDemo2 {
public static void main(String[] args) {
// 定义数组
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] arr2 = { 11, 22, 33, 44, 55, 66, 77, 88 };

    // 复制数组    // System.arraycopy(arr, 0, arr2, 0, 8);    // System.arraycopy(arr, 0, arr2, 0, 80);    System.arraycopy(arr, 2, arr2, 2, 2);    for (int x = 0; x < arr.length; x++) {        System.out.println(arr[x]);    }    System.out.println("---------------------------");    for (int x = 0; x < arr2.length; x++) {        System.out.println(arr2[x]);    }}

}
Date类

Date:日期类
Date 表示特定的瞬间,精确到毫秒。
public class Date extends Object implements Serializable, Cloneable, Comparable
Date类的构造方法

Date()
Date(long date)

import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
// 方式1
Date d = new Date();
// Thu Aug 14 14:39:15 CST 2014
System.out.println(d);

    // 方式2    // Date d2 = new Date(120000);    // System.out.println(d2);    long time = System.currentTimeMillis();    // Thu Aug 14 14:43:18 CST 2014    Date d2 = new Date(time);    System.out.println(d2);}

}
Date类的成员方法:

public void setTime(long time)
设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
public long getTime()
返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
获取当前时间的毫秒值:
A:Date getTime()
B:System currentTimeMillis()
设置当前时间的毫秒值:

A:Date Date(long time)
B:Date setTime(long time)

import java.util.Date;
public class DateDemo2 {
public static void main(String[] args) {
Date d = new Date();

    long time = d.getTime();    long time2 = System.currentTimeMillis();    System.out.println(time == time2);    System.out.println(d);    d.setTime(1234567);    System.out.println(d);}

}
DateFormat类

DateFormat是一个抽象类
public abstract class DateFormat extends Format

DateFormat:

格式化:
Date – String
public final String format(Date date)
yyyy年MM月dd日 HH:mm:ss
解析:
String – Date
public Date parse(String source)
DateFormatDemo.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatDemo {
public static void main(String[] args) throws ParseException {
// Date – String
Date d = new Date();

    // SimpleDateFormat()    // DateFormat df = new SimpleDateFormat();    // 默认的模式    // SimpleDateFormat sdf = new SimpleDateFormat();    // 指定模式    // SimpleDateFormat(String pattern)    // 模式字符串的组成规则:2014年8月14日 15:18:22    // yyyy年MM月dd日 HH:mm:ss    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");    String s = sdf.format(d);    System.out.println(s);    // String -- Date    String ss = "2014-08-14 15:21:12";    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    Date dd = sdf2.parse(ss);    System.out.println(dd);}

}
日期工具类的创建和使用

DateUtil.java

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* 这是针对日期进行操作的工具类
*
* @author charlie
* @version V1.0
*/
public class DateUtil {
private DateUtil() {
}

/** * 这个方法的作用是把日期转成字符串类型 *  * @param date *            被转换的日期 * @return 字符串的表达形式 格式是:2014年04月09日 12:23:34 */public static String dateToString(Date date) {    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");    return sdf.format(date);}/** * 这个方法的作用是把日期转成字符串类型 *  * @param date *            被转换的日期 * @param format *            被转换的格式 * @return 字符串的表达形式 格式你给出的形式 */public static String dateToString(Date date, String format) {    SimpleDateFormat sdf = new SimpleDateFormat(format);    return sdf.format(date);}

}
DateUtilDemo.java

import java.util.Date;

public class DateUtilDemo {
public static void main(String[] args) {
Date d = new Date();

    String s = DateUtil.dateToString(d);    System.out.println(s);    String ss = DateUtil.dateToString(d, "yyyy");    System.out.println(ss);    String sss = DateUtil.dateToString(d, "yyyy年MM月dd日");    System.out.println(sss);}

}
Calendar:日历类

可以单独的表示任意的一个数据信息,把日历字段和对应的值进行一个转换。
public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable
Calendar是抽象类,实现Serializable, Cloneable, Comparable的接口
Calendar类的成员方法

A:获取日历字段对应的值。
public int get(int field)返回给定日历字段的值
实例

import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
// 创建对象
Calendar rightNow = Calendar.getInstance(); // 多态
// System.out.println(rightNow);

    // public static final int YEAR    int year = rightNow.get(Calendar.YEAR);    int month = rightNow.get(Calendar.MONTH);    int date = rightNow.get(Calendar.DATE);    int hour = rightNow.get(Calendar.HOUR);    int minute = rightNow.get(Calendar.MINUTE);    int second = rightNow.get(Calendar.SECOND);    // String s = (second > 9) ? second + "" : "0" + second;    StringBuilder sb = new StringBuilder();    sb.append(year).append("年").append(month + 1).append("月").append(date)            .append("日").append(hour).append(":").append(minute)            .append(":").append(second);    String result = sb.toString();    System.out.println(result);}

}
B:设置时间的年月日

public final void set(int year,int month,int date)
C:根据日历的规则,为给定的日历字段添加或减去指定的时间量。
public void add(int field,int amount)
实例

import java.util.Calendar;
public class CalendarDemo2 {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();

    // public final void set(int year,int month,int date)    // 需求:把日期设置为2008年8月8日    c.set(2008, 7, 8);    // 需求:设置2010年的8月8日    c.add(Calendar.YEAR, 2);    c.add(Calendar.YEAR, -12);    c.add(Calendar.MONTH, 3);    c.add(Calendar.DATE, 11);    int year = c.get(Calendar.YEAR);    int month = c.get(Calendar.MONTH);    int date = c.get(Calendar.DATE);    StringBuilder sb = new StringBuilder();    sb.append(year).append("年").append(month + 1).append("月").append(date)            .append("日");    String result = sb.toString();    System.out.println(result);}

}
Calendar类的练习:

需求:给出任意一个年份,请你给出该年的2月份有多少天?

import java.util.Calendar;
import java.util.Scanner;
public class CalendarDemo3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入年份:”);
int year = sc.nextInt();

    Calendar c = Calendar.getInstance();    c.set(year, 2, 1); // 设置给定的年的3月1日    c.add(Calendar.DATE, -1); // 往前推一天    System.out.println(c.get(Calendar.DATE));}

}
抽象类如何返回本身的对象呢

abstract class Fu {

public static Fu getFu() {    Fu f = new Zi();    return f;}

}

class Zi extends Fu {

}

Fu f = Fu.getFu();

0 0