码迷,mamicode.com
首页 > Windows程序 > 详细

常用API的使用

时间:2017-03-12 16:50:11      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:子类   false   参数   ...   表示   oda   垃圾回收   属性   包含   

Scanner类】

  Scanner:JDK5以后出现,用于接受键盘录入的数据。

Scanner类的使用】

1、导包。(API中出了java.lang包外,使用都需要导包)

    import java.util.Scanner;

2、创建对象

    Scanner sc = new Scanner (System.in);

3、输入数据

    Eg:数字型:int a = sc.nextInt();

   字符串:String str = sc.nextLine();

注意:System类下有一个静态的成员变量:in

Public static final InputStream in:表示一个标准的输入流,代表键盘输入。

 

【问题,输入基本数据类型和字符串的细节

  String----->String : 没问题

  String----->int  : 没问题

  int  ---- > int   : 没问题

  int ------>String  : 有问题。因为会把换行符给String(windows下,换行符是:\r\n)

   转义字符:有些字符本身有自己的意思,为了表示特殊的含义,用\

   转意。

  如何解决:重新创建一个对象即可(把所有的类型当做String类型,用到什么类型再转)。

 

String类】

String代表字符串(由多个字符组成的一串数据),其本质是字符数组。

注意:所有的字符串字面值都可以看做一个字符串对象。

字符串是常量;值在创建之后不可以更改(引用可以改变)。

字符串常量在编译时,存储到了class文件的常量代码中。JVM加载class文件时,将这些常量都存储到内存的常量池(方法区)中。

String构造方法】

 * String():无参构造方法

 * String(byte[] bytes):字节数组转成字符串

 * String(byte[] bytes, int startIndex, int length):把字节数组的一部分转成字符串

 * String(char[] value):把字符数组转成字符串

   char[] chs = {‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘‘,‘‘,‘‘,‘‘,‘‘,‘‘};

   String s4 = new String(chs);

 * String(char[] value, int startIndex, int length):把字符数组的一部分转成字符串

 * String(String original):把字符串转成字符串。

字符串的长度功能:public int length()

 

【呵呵】

1、字符串一旦初始化,就不可以改变。内容不变,但是引用可变。

2String s1 = new String(“abc”);String s2 = “abc”;有区别吗?

答:第一种方式,在内存中有两个对象(会在堆内存中创建字符串对象,将这个字符串常量作为参数传递给了String的构造函数,而字符串参数在常量池中);第二种方式只有一个对象。

方法区有个常量池,字符串定义时会到常量池中找,有的话拿来用没有再造。

3看程序,写结果

 * 请注意:如果直接赋值,是从常量池里先找,如果有,就用。否则,就造一个。

 * String s1 = new String("hello");

 * String s2 = new String("hello");

 * System.out.println(s1 == s2); // false,两个对象

 * System.out.println(s1.equals(s2)); // true//复写了objectequals方法,比较内容

  System.out.println(s1==s2.intern());//true:intern();返回字符串对象的规范化表示形式。

 * String s3 = "hello";

 * String s4 = "hello";

 * System.out.println(s3 == s4); // true//地址池中有

 * System.out.println(s3.equals(s4)); // true

 * String s5 = new String("hello");//两个对象

 * String s6 = "hello";//一个对象

 * System.out.println(s5 == s6); // false

 * System.out.println(s5.equals(s6)); // true

 

4  看程序,写结果

 * 如果是变量,直接造。

 * 如果是常量,先找,有就用。没有就造。

String s7 = "hello";

String s8 = "world";

String s9 = "helloworld";

System.out.println(s9 == s7 + s8);// false 变量

System.out.println(s9.equals(s7 + s8));// true

System.out.println(s9 == "hello" + "world");// true 常量

System.out.println(s9.equals("hello" + "world"));// true

String类常用功能】

判断功能:

 * boolean equals(Object obj):比较字符串的内容是否相同。

  EgString s = “a”;  : s.equals(“hello”);

 * boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,不区分大小写。

 * boolean  contains(String str):判断该字符串对象是否包含给定的字符串。

 * boolean  startsWith(String str):判断该字符串对象是否以给定的字符串开头。

 * boolean  endsWith(String str):判断该字符串对象是否以给定的字符串结束。

 * boolean  isEmpty():判断该字符串对象是否为空。指的是内容("")是地址(null)(异常)

 

获取功能:

 * int  length():返回该字符串对象的长度。

 * char charAt(int index):返回指定索引处的字符。

 * int  indexOf(int ch):返回指定字符第一次出现的索引位置。   97,‘a‘

 * int  indexOf(String str):返回指定字符串第一次出现的索引位置。

 * int  indexOf(int ch,int fromIndex):从指定位置开始返回指定字符第一次出现的索引位置。

 * int  indexOf(String str,int fromIndex):从指定位置开始,返回指定字符串第一次出现的索引位置。

 * String substring(int start):从指定位置开始截取字符串。

 * String substring(int start,int end):从指定位置开始,到指定位置结束截取字符串。 包左不包右。

 

转换功能:

* byte[] getBytes():把该字符串转换成字节数组。

  String s = "AbCde";

  byte[] bys = s.getBytes();

 * char[]  toCharArray():把该字符串转换成字符数组。

  char[] chs = s.toCharArray();

 * static String copyValueOf(char[] chs):把字符数组转换成字符串。

 * static String valueOf(char[] chs):把字符数组转换成字符串。

  String s2 = String.valueOf(chs);//chs 为数组。

  System.out.println(s2);

 * static String valueOf(int i):把int类型的数据转换字符串。

 * 注意:字符串的一个valueOf功能,可以把任意的其他类型转换字符串。

 * String  toLowerCase():把字符串转成小写。

 * String  toUpperCase():把字符串转成大写。

 * String  concat(String str):字符串的拼接。

 

替换功能:

 * String replace(char old,char new):把该字符串中的指定字符用新的指定字符替换。

 * String replace(String old,String new):把该字符串中的指定字符串用新的指定字符串替换。

 *

分割功能:

 * String[] split(String regex):把字符串按照指定的标记分割成字符串数组。

 *

去除字符串两端的空格:

 * String trim()

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

 * int compareTo(String str)

 * int compareToIgnoreCase(String str)

 
技术分享
 1 //练习:获取 字符串中 指定字符串 的位置和个数
 2 //        思路:
 3 //        1,无非就是在一个字符串中查找另一个字符串。indexOf。
 4 //        2,查找到第一次出现的指定字符串后,如何查找第二个呢?
 5 //        3,无需在从头开始,只要从第一次出现的位置+要找的字符串的长度的位置开始向后查找下一个第一次出现的位置即可。
 6 //        4,当返回的位置是-1时,查找结束。
 7 public class StringTests1 {
 8     public static void main(String[] args) {
 9         String str = "jflxtaolljlxtaodghlxtaodk";
10         String key = "lxtao";
11         getIndex(str, key);
12     }
13 
14     public static void getIndex(String str, String key) {
15         int index = 0;
16         int content = 0;
17         //while()的条件是,只要返回的 位置不是-1,就继续循环着找。因为找不到才会返回-1;
18         while ((index = str.indexOf(key, index)) != -1) {
19             System.out.println(index + "\t");
20             index = index + key.length(); //基于上次的位置查找。
21             content++;
22         }
23         System.out.println("个数为" + content);
24     }
25 }
26 
27 
28 //练习:"lxtao"按照长度递减的方式获取出所有的连续字符串。
29 public class StringTest2 {
30     public static void main(String[] args) {
31     /*
32      *  lxtao 5   0~length-0 //取到length ,因为含头不含尾
33      *  lxta xtao 4   0~length-1 1~length
34      *  lxt xta tao 3   0~length-2 1~length-1 2~length
35      */
36         String str = "lxtao";
37         printSubString(str);
38     }
39 
40     public static void printSubString(String str) {
41         for (int i = 0; i < str.length(); i++) {
42             // 从0 开始取,取到length-i,当end大于了长度+1,就结束
43             for (int start = 0, end = str.length() - i; end < str.length() + 1; start++, end++) {
44                 String temp = str.substring(start, end);
45                 System.out.print(temp + "\t");
46             }
47             System.out.println();
48         }
49     }
50 }
51 
52 
53 //练习:"sdjflsitlxtaokdjfdsf""ertitlxtaoewtr"获取两个字符串中最大相同的子串。面试题
54 
55 public class StringTest4 {
56     public static void main(String[] args) {
57     /*
58      * 如何确定哪个字符串是短的。 思路:参阅练习三。
59      * 其实就是将短的字符串,不断的从长到短获取,每获取一次就到长的串中判断是否存在,如果存在,找到了。
60      */
61         String s1 = "sdjflsitlxtaokdjfdsf";
62         String s2 = "ertitlxtaoewtr";
63         String maxSubstring = getMaxSubstring(s1, s2);
64         System.out.println("max=" + maxSubstring);
65     }
66 
67     public static String getMaxSubstring(String s1, String s2) {
68 
69         // 判断两个字符串,明确长字符串和短字符串。
70         String max, min;
71         max = s1.length() > s2.length() ? s1 : s2;
72         min = max.equals(s1) ? s2 : s1;//max是s1,把s2赋值给min
73         // 获取短字符串中长度由长到短。
74         for (int i = 0; i < min.length(); i++) {
75             for (int a = 0, b = min.length() - i; b < min.length() + 1; a++, b++) {
76                 String temp = min.substring(a, b);
77                 if (max.contains(temp)) {
78                     return temp;
79                 }
80             }
81         }
82 
83         //循环结束也没有找到相同的,就返回null
84         return null;
85     }
86 
87 }
View Code

 

【排序,查找Arrays工具类】

【冒泡排序】

冒泡排序:从第一个索引开始,到length-1(最后一个没得换)相邻两个元素比较,当满足条件----置换位置。这样大的数字就排到了后面,以此类推,就得到了升序的数组。

 1 public static void bubbleSort(char[]chs){
 2 // 外循环控制 要比较的次数(length-1)。
 3     for(int i=0;i<chs.length-1;i++){
 4 // 内循环控制每次比较的细节。相邻元素两两相比,大的置后。-1是因为最后一个不需要往后比,避免角标越界。-i,每比一次大的就靠后,不用再参与比较。
 5         for(int j=0;j<chs.length-1-i;j++){
 6             if(chs[j]>chs[j+1]){
 7                 char temp=chs[j];
 8                 chs[j]=chs[j+1];
 9                 chs[j+1]=temp;
10             }
11         }
12     }
13 }

 

【选择排序】

选择排序:拿第一个元素,依次与剩余的元素进行比较。满足条件就置换位置(小的数值在靠前),再从第二个元素开始,依次与剩余的元素比较,………………

 1 public static void selectSort(char[] chs) {
 2     // 比较次数
 3     for (int i = 0; i < chs.length - 1; i++) {
 4         // 相邻元素比较,所以+1;小的靠前。
 5         for (int j = i + 1; j < chs.length; j++) {
 6             if (chs[i] > chs[j]) {
 7                 char temp = chs[i];
 8                 chs[i] = chs[j];
 9                 chs[j] = temp;
10             }
11         }
12     }
13 }

【二分查找】

前提:数组必须是有序数组。

原理:从中间位置开始比较。

相等,就直接返回该处的索引;

大于,往右边找;

小于,往左边找;

……

 

 1 public static int getIndex2(int[]arr,int value){  //91
 2     int start=0;
 3     int end=arr.length-1; //4
 4     int mid=(start+end)/2; //2
 5     while(arr[mid]!=value){
 6         if(value>arr[mid]){
 7             start=mid+1; //3,4
 8         }else if(value<arr[mid]){
 9             end=mid-1;
10         }
11         //如果找不到,就返回-1。
12         if(start>end){
13             return-1;
14         }
15         mid=(start+end)/2;  //3,4
16      }
17     return mid;
18 }

 

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)

 

StringBuffer&StringBulider类】

StringBuffer:字符串缓冲区类。

StringStrigBuffer的区别】

String:长度是固定的,一旦拼接就会产生一个新的字符串,以前的就会浪费掉。

StringBuffer:长度可变在原来的空间是可以扩充的,被称为字符串缓冲区。

StringBufferStringBuilder的区别】特有功能:翻转

相同点:都是字符串缓冲区,功能一模一样。

不同点:StringBuffer:同步,效率低。

StringBulider:不同步,效率高。

【构造方法】

  1. StringBuffer() 初始容量:16字符。
  2. StringBuffer(int capacity) 指定容量
  3. StringBuffer(String str) 指定容量???。

【掌握的方法】

A. public int length().实际存储值。

B. public int capacity().理论存储值。

  EgStringBuffer sb = new StringBuffer();

  System.out.println(sb.length());//0

  System.out.println(sb.capacity());//16

  System.out.println("--------------");

// 方式2

  StringBuffer sb2 = new StringBuffer(50);

  System.out.println(sb2.length());//0

  System.out.println(sb2.capacity());//50

  System.out.println("--------------");

// 方式3

//相反:StringBuffer转换为字符串String(StringBuffer buffer)

//很多时候,我们会看到类之间的相互转换,请问为什么要转换?就是为了用别人的方法。

// String转换为StringBuffer的方式。

  StringBuffer sb3 = new StringBuffer("helloworld");

  System.out.println(sb3.length());

  System.out.println(sb3.capacity());

A:添加功能

  public StringBuffer append(String str):在后面追加元素,返回当前对象的引用。

      StringBuffer buffer = new StringBuffer();

// 添加数据

 StringBuffer buffer2 = buffer.append("hello");

 System.out.println(buffer == buffer2);// true

B:插入功能

  public StringBuffer insert(int offset,String str):在指定位置插入元素,返回当前对象的引用。

// 链式编程

buffer.append("hello").append(true).append(12345).append(23.567);

 

C: 删除功能

  public StringBuffer delete(int start,int end):删除从指定位置开始到指定位置基数的数据,返回当前对象的引用。

    public StringBuffer deleteCharAt(int index):删除指定索引处的一个字符,返回当前对象的引用。

技术分享
 1 public class StringBufferDemo3 {
 2     public static void main(String[] args) {
 3       // 创建字符串缓冲区对象
 4       StringBuffer buffer = new StringBuffer();
 5       buffer.append("helloworld").append(true);
 6       // 把world删除掉
 7       buffer.delete(5, 10); // 包左不包右。
 8       buffer.deleteCharAt(2);
 9       //我要把数据清空
10       //buffer = new StringBuffer();
11       buffer.delete(0, buffer.length());
12       System.out.println("buffer:" + buffer);
13     }
14 }
View Code

 

  替换功能:

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

    把从指定位置开始到指定位置结束的内容用一个新的字符串替换,返回当前对象的引用。

   截取功能:

    public String substring(int start):截取从指定位置开始到末尾的数据并返回。

   public String substring(int start, int end):截取从指定位置开始到指定位置结束的数据并返回。

  反转功能:

    public StringBuffer reverse():把字符串缓冲区对象的数据反转。

【字符串和字符串缓冲区的相互转换】

   String -- StringBuffer

   A:StringBuffer buffer = new StringBuffer(String s);

    B:StringBuffer buffer = new StringBuffer();

        buffer.append(String s);

   

   StringBuffer -- String

    A:String s = new String(StringBuffer sb);

    B:String s = (StringBuffer s).toString();

 

int[] arr = {34,12,89,68};将一个int[]中元素转成字符串  格式 [34,12,89,68]

public static String toString_2(int[] arr) {

StringBuffer sb = new StringBuffer();

sb.append("[");

for (int i = 0; i < arr.length; i++) {

if(i!=arr.length-1){

sb.append(arr[i]+",");

}else{

sb.append(arr[i]+"]");

}

}

return sb.toString();//转成字符串表现形式

}

 

 

练习:对字符串中的字符进行自然排序

"cfdasbv"--->"abcdfsv"

思路:

1,排序我熟,但是都是对数组排序。

2,数组中的元素在哪里呢?在字符串中,把字符串转成数组。

3,对数组排序。

4,将排序后数组转成字符串。

public static String sortStringByChar(String str) {

//1,将字符串转成数组。转成字符数组。

char[] chs = getArray(str);

//2,对数组排序。

sort(chs);

//3,将排序后的数组转成字符串。

return new String(chs);

}

//数组排序

private static void sort(char[] chs) {

Arrays.sort(chs);

}

//将字符串转成字符数组

private static char[] getArray(String str) {

 

return str.toCharArray();

   }

 

练习:模拟Stringtrim方法

 

public static String myTrim(String str) {

// 1,定义两个变量。一个记录头的位置,一个记录尾的位置。

int start = 0;

int end = str.length() - 1;

// 2,获取头部非空白的位置。

while (start <= end && str.charAt(start) == ‘ ‘) {

start++;

}

// 3,获取尾部非空白的位置。

while (start <= end && str.charAt(end) == ‘ ‘) {

end--;

}

// 4,根据获取头和尾非空格的位置。截取字符串。

return str.substring(start, end + 1);

}

 

 

【基本数据类型包装类】

针对基本数据类型,只能做一些简单的算术操作,如果相对其进行复杂的操作,就用到Java提供的针对基本数据类型的包装类。

好处:可以使用属性和方法对其操作。

基本数据类型

对应的包装类

byte

Byte

short

Short

char

Character

int

Integer

long

Long

float

Float

double

Double

boolean

Boolean

 

【举例:Integer类】

Integer类的构造方法

Integer(int value):把一个int类型包装成一个Integer类型

Integer(String s):把一个String类型包装成一个Integer类型

注意:这里的字符串必须是由数字字符组成。

// 方式1

int num = 10;

Integer i = new Integer(num);

System.out.println(i);

// 方式2

String s = "10";

Integer ii = new Integer(s);

System.out.println(ii);

int&String间的转换】

【基本类型转字符串int –> String

方式一:与””拼接

方式二:调用  String  valueOf();功能

方式三:调用 包装类 toString();方法。

 * String.valueOf(int x)

 * Integer.toString(int x)

// int -- String

int number = 10;

// 方式1

String s = number + "";

System.out.println(s);

//方式2

String s2 = String.valueOf(number);

System.out.println(s2);

//方式3

//int -- Integer -- String

Integer i = new Integer(number);

String s3 = i.toString();

System.out.println(s3);

//方式4

//public static String toString(int i)

String s4 = Integer.toString(number);

System.out.println(s4);

System.out.println("--------------");

 

【字符串转基本类型 String à int 

方式一:Integer.parseInt(String s)

   方式二:String  Integer -- int

//方式1

//public static int parseInt(String s)

int nn = Integer.parseInt(45);

System.out.println(nn);

 

//方式2

//String -- Integer -- int

String ss = "100";

Integer ii = new Integer(ss);

//public int intValue()

int n = ii.intValue();

System.out.println(n);

 

【基本数值à包装类:】

方式一:Integer i = new Integer(4);//使用构造函数函数

方式二:Integer ii = new Integer("4");//构造函数中可以传递一个数字字符串

方式三:Integer iii = Integer.valueOf(4);//使用包装类中的valueOf方法

 

【包装类转基本数值】

Integer i = new Integer(4);

int num =  i.intValue();

【自动装箱拆箱】

此为JDK5以后的新特性。

 * 自动装箱:从int—Integer

 * 自动拆箱:从Integer—int

* 注意:自动装箱和拆箱确实简化了操作,但是有一个隐含问题,就是最好要先做对象不为null的判断。

// JDK4以前的做法

// Integer i = new Integer(100);

// i = new Integer(i.intValue()+200);

 

// JDK5以后的做法

Integer i = 100; // 自动装箱。等价于 Integer i = new Integer(100);

i = i + 200;

// i + 200,参与运算,要求类型一致。所以,它们肯定有一个转换类类型。

// 那么是谁转换了呢?肯定是i变成了基本类型。i.intValue() 自动拆箱。

// i = i.intValue()+200 自动装箱。

System.out.println(i);

 

// 怎么测试一下,能够知道这里肯定是真的调用方法了呢?

// Integer ii = null;

// // java.lang.NullPointerException

//

// // 遇到使用对象,请先判断是否为null

// if (ii != null) {

// ii = ii + 200;

// System.out.println(ii);

// }

 

 题:byte常量池

 * 自从有了自动装箱后,在byte范围内的值直接赋值给包装类的时候,是从常量池里获取的byte一个字节,计算机以字节为单位存储,字节重复的最多)

 */

public class IntegerTest {

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

 

Math 类】

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

static double

abs(double a) 返回 double 值的绝对值。

static double

 

ceil(double a)
返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数

static double

 

floor(double a)
返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。

static double

 

pow(double a, double b)
返回第一个参数的第二个参数次幂的值

static double

 

random()
返回带正号的 double 值,该值大于等于 0.0 且小于 1.0

static int

 

round(float a)
返回最接近参数的 int

static long

 

max(long a, long b)
返回两个 long 值中较大的一个。

static double

 

min(double a, double b)
返回两个 double 值中较小的一个。

 

Random类】

/*

 * Random:是产生随机数的类。跟种子相关。

 *

 * 构造方法:

 * Random():没有给种子产生随机数,默认种子是当前时间的毫秒值。

 * Random(long seed):给定种子产生随机数。如果种子相同,那么, 将产生相同的随机数。

 *

 * 要掌握的功能:

 * public int nextInt()int范围内的随机数。

 * public int nextInt(int n):获取的是[0,n)之间的随机数。

 */

public class RandomDemo {

public static void main(String[] args) {

// 不给种子

// Random r = new Random();

// 给种子

Random r = new Random(250);

 

// 表示我要生成10[0,100)之间的随机数

for (int x = 0; x < 10; x++) {

System.out.println(r.nextInt(100));

}

}

}

==equals的区别】

答:==可以比较基本数据类型(比较的是数值是否相等),也可比较引用数据类型(比较地址池)。

equals 只能比较引用数据类型,比较的是地址池是否相等。如果要比较内容需要复写equals方法。

当使用==时,为了避免错写成=,可把常量写在左边。Eg20==a;

s.equals(hello);hello.equals(s);的区别(s为字符串):

前者s=null;时会报NullPointerException.后者不回。

 

【正则表达式】

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

pattern类:正则表达式的编译表示形式。

boolean

matches(String regex) String类中的方法。判断功能。
          告知此字符串是否匹配给定的正则表达式

Eg:判断是否是电话号码。

String phone = “13823243423”;

String regex=”1[38]\\d{9};// boolean flag = phone.matches(regex);

 

字符串的切割:

Eg

String str = “12 34   54    23    2”;//空格不确定

String regex = “ +”;//+表示一次或多次

  String[] strArr=str.split(regex);//去空格(不确定个数);

 

去叠词:String str=addddaaddffdfdfdfsl”;

String regex = (.)\\1+;//1表示组

String[] strArr = str.split(regex);

 

替换功能:

public String replaceAll(String regex,String replacement)

String str = "sdaaafghccccjkqqqqql";

String regex = "(.)\\1+";

String result = str.replaceAll(regex, "#");

 

将叠词变成一个:

String regex = (.)\\1+;

String result3 = str3.replaceAll(regex3, "$1");

 

治口吃:

String str =" 我我...........要要...要学....学学.....编编......";

String result=str.replaceAll("\\.", "");

System.out.println(result);

String regex = "(.)\\1+";

String strs = result.replaceAll(regex, "$1");

System.out.println(strs);

 

Pattern:正则表达式的编译表达形式】

//把正则表达式编译成模式对象

public static Pattern compile(Stirng regex)

典型的调用步骤:

  1. Pattern p = Pattern.compile(“a*b”);//a出现1到多次,b出现一次
  2. Matcher m = p.matcher(“aaab”);
  3. boolean b = m.matches();

如果仅仅为了做判断,用普通的字符串总能就能实现?

String str = “aaab”;

Stirng regex = “a*b”;

boolean flag = str.matches(regex);

使用pattern,是为了使用它的获取功能。

EgString str = da jia zhu yi le, ming tian bu fang jia,xie xie;获取str3个字母的单词。

String str = da jia zhu yi le, ming tian bu fang jia ,xie xie;

String regex = \\b[a-z]{3}\\b;//\\b表示单词的边界

Pattern p = Pattern.compile(regex);//得到模式对象

Matcher m = p.matcher(str);//得到匹配器对象

while(m.find)//find(); 尝试查找与该模式匹配的输入序列的下一个子序列。
{

System.out.println(m.group());//返回由以前匹配操作所匹配的输入子序列。

}

 

Date日期类】

Date 表示特定的瞬间,精确到毫秒。

Date构造方法】

  1. Date();//获取当前日期(注意有同名的类,其使用的是java util包下的)

Long time = d.getTime();//通过日期得到毫秒值

  1. Date(long date);//将给定的毫秒值转换成日期对象

DateFormat类抽象类】

//获取日期格式器对象,在获取格式器对象时可以指定风格,风格包括 FULLLONGMEDIUM SHORT

DateFormat format = DateFormat.getDateInstance(DateFormat.LONG);

//对日期进行格式化

String str_time = format.format(date);

   System.out.println(str_time);//20131211

 

 

【子类SimpleDateFormat

DateFormat:在StirngDate间进行转换的抽象类。

SimpleDateFormatSimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。

 

String ---- Date

public Date parse(String source)

注意:要解析成的模式字符串一定要和字符串本身匹配。

Date ---- String

public final String format(Date date)

注意:需要什么格式,就给出什么格式化的模式字符串。

public class DateFormatDemo {

public static void main(String[] args) throws ParseException {

// 创建日期

Date d = new Date();

String str = dateToString(d, "yyyyMMddHH:mm:ss");

System.out.println(str);

 

//创建一个字符串

String s = "2014-03-06 10:04:22";

Date dd =  stringToDate(s,"yyyy-MM-dd HH:mm:ss");

System.out.println(dd);

}

 

public static Date stringToDate(String str,String format) throws ParseException {

// String s = "2014-03-06 10:04:22";

// //System.out.println(s);

// //public Date parse(String source)

// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Date dd = sdf.parse(s);

// System.out.println(dd);

return new SimpleDateFormat(format).parse(str);

}

public static String dateToString(Date date, String format) {

//  Date -- String

// 创建一个日期对象

// Date d = new Date();

// // 格式化

// // public final String format(Date date)

//  SimpleDateFormat()

// // DateFormat df = new SimpleDateFormat(); //多态

// // SimpleDateFormat sdf = new SimpleDateFormat(); // 用默认的模式 //

// // 用给定模式

// // SimpleDateFormat(String pattern)

// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");

// // 模式我不会给

// String str = sdf.format(d);

// System.out.println(str);

// SimpleDateFormat sdf = new SimpleDateFormat(format);

// return sdf.format(date);

return new SimpleDateFormat(format).format(date);

}

}

Calendar类】

Calendar:表示一个日期的抽象类,可以更精确的得到每一个日历字段(年月日,时分秒)。

  1. 如何获取每一个日历字段对应的数据?

public int get(int field)//返回给定日历字段的值

  1. 其他方法

* public final void set(int year,int month,int date)

 * public abstract void add(int field,int amount):根据给定的日历字段及其对应的值改变数据。

public class CalendarDemo {

public static void main(String[] args) {

Calendar rightNow = Calendar.getInstance(); // 右边得到的肯定是子类对象。

// rightNow.add(Calendar.YEAR, 3);

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;

// 201432610:42:46

StringBuilder sb = new StringBuilder();

sb.append(year).append("").append(month + 1).append("").append(date)

.append("").append(hour).append(":").append(minute)

.append(":").append(second > 9 ? second : "0" + second);

System.out.println(sb.toString());

// 需求:请根据我给定的年,判断这年的2月有多少天?

Calendar c = Calendar.getInstance();

Scanner sc = new Scanner(System.in);

System.out.println("请输入年份:");

int y = sc.nextInt();

c.set(y, 2, 1); // 这是y年的31

c.add(Calendar.DATE, -1); // 三月一日的前一天

int d = c.get(Calendar.DATE);

System.out.println(d);

}

}

System类】

System:系统类,提高了静态的成员供我们使用。

* public static void gc():运行垃圾回收器。

 * public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。

 * public static long currentTimeMillis():返回以毫秒为单位的当前时间。

 

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

public class SystemDemo {

public static void main(String[] args) {

// 请问我想知道我的一段代码的执行时间,怎么办?

long start = System.currentTimeMillis();

for (int x = 0; x < 100000; x++) {

System.out.println(x);

}

long end = System.currentTimeMillis();

System.out.println((end - start) + "毫秒");

}

}

 

 

package cn.itcast_02;

 

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

 

/*

 * DateFormat:StringDate间进行转换的抽象类。

 *

 * String -- Date

 * public Date parse(String source)

 * 注意:你要解析成的模式字符串一定要和字符串本身匹配。

 *

 * Date -- String

 * public final String format(Date date)

 * 注意:你需要什么格式,就应该给出什么格式化的模式字符串。

 */

public class DateFormatDemo {

public static void main(String[] args) throws ParseException {

// 创建日期

Date d = new Date();

String str = dateToString(d, "yyyyMMddHH:mm:ss");

System.out.println(str);

 

//创建一个字符串

String s = "2010-11-21 10:11:11";

Date dd =  stringToDate(s,"yyyy-MM-dd HH:mm:ss");

System.out.println(dd);

 

String s2= "2014-04-03 12:11:11";

Date d2 = stringToDate(s2,"yyyy-MM-dd HH:mm:ss");

 

 

int day = getDay(dd,d2);

System.out.println(day);

}

 

public static int getDay(Date dd, Date d2) {

return (int) ((d2.getTime()-dd.getTime())/1000/3600/24);

 

}

 

public static Date stringToDate(String str,String format) throws ParseException {

// String s = "2014-03-06 10:04:22";

// //System.out.println(s);

// //public Date parse(String source)

// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Date dd = sdf.parse(s);

// System.out.println(dd);

return new SimpleDateFormat(format).parse(str);

}

public static String dateToString(Date date, String format) {

//  Date -- String

// 创建一个日期对象

// Date d = new Date();

// // 格式化

// // public final String format(Date date)

//  SimpleDateFormat()

// // DateFormat df = new SimpleDateFormat(); //多态

// // SimpleDateFormat sdf = new SimpleDateFormat(); // 用默认的模式 //

// // 用给定模式

// // SimpleDateFormat(String pattern)

// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");

// // 模式我不会给

// String str = sdf.format(d);

// System.out.println(str);

// SimpleDateFormat sdf = new SimpleDateFormat(format);

// return sdf.format(date);

return new SimpleDateFormat(format).format(date);

}

}

常用API的使用

标签:子类   false   参数   ...   表示   oda   垃圾回收   属性   包含   

原文地址:http://www.cnblogs.com/lxtao369/p/6538074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!