1. 程式人生 > 實用技巧 >Java從入門到實戰之(3)常用類與方法

Java從入門到實戰之(3)常用類與方法

下面我們介紹Java類庫所提供的常用類及類的常用方法

一、java.lang.String

1. String類常用的建構函式

public String(String original)

使用串物件original,建立字串物件,其中original可以是字串常量或字串物件

public String(char value[])

使用字元陣列value,建立一個字串物件

public String(char value[],int offset,int count)

從字元陣列value下標為offset的字元開始,建立還有count個字元的字串物件

public String(StringBuffer buffer)

使用StringBuffer類的物件buffer,建立一個字串物件

我們上下程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String1 {
 4     public static void main(String[] args) {
 5         String s1 = new String("ascd");
 6         String s2 = new String(s1);
 7         
 8         char[] value = new char[]{'a','b','c'};
9 String s3 = new String(value); // 複製整個陣列 10 String s4 = new String(value,1,2); // 建立字串"bc" 11 System.out.println(s1); 12 System.out.println(s2); 13 System.out.println(s3); 14 System.out.println(s4); 15 } 16 }

執行結果:

ascd
ascd
abc
bc

2.String類常用的方法一:

public char charAt(int index)


返回字串中index位置處的字元,index從0開始

public int compareTo(String anotherString)
比較當前字串與anotherString字串的大小。若當前字串大,則返回正整數;當前字串小,則返回一個小於0的整數;若兩者相等,則返回0

public int compareToIgnoreCase(String anotherString)
比較兩個字串的大小,比較時,忽略大小寫;返回結果和compareTo方法一致

public String concat(String str)
在當前字串尾部追加字串str,並返回連線後的新字串

public boolean endsWith(String suffix)
若當前字串以字串suffix結尾,則返回true,否則返回false

public boolean equals(Object anObject)
若當前字串物件與anObject擁有相同的字串時,返回true,否則返回false

public boolean equalsIgnoreCase(String anotherString)
功能同equals(),但比較兩字串時,忽略大小寫

我們上下程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String s1 = new String("ABCDEFG");
 6         System.out.println(s1.charAt(2));
 7         System.out.println(s1.compareTo("abc"));
 8         System.out.println(s1.compareToIgnoreCase("abcdefg"));
 9         System.out.println(s1.concat("123"));
10         System.out.println(s1.endsWith("fg"));
11         System.out.println(s1.endsWith("FG"));
12         System.out.println(s1.equals("ABCDEFG"));
13         System.out.println(s1.equalsIgnoreCase("abcdefg"));
14     }
15 }

執行結果:

C
-32
0
ABCDEFG123
false
true
true
true

3.String類常用的方法二:

int indexOf(int ch)
返回指定字元ch在此字串中第一次出現的位置下標(下標從0開始)。若找不到,則返回-1

int indexOf(int ch,int fromIndex)
從當前字串中下標為fromIndex處開始查詢字元ch,並返回ch在字串中首次出現的位置座標。

int indexOf(String str)
返回字串str在當前字串中首次出現的位置下標

int indexOf(String str,int fromIndex)
從當前字串中下標為fromIndex處開始查詢字串str,並返回字串str在當前字串中首次出現的位置下標

各自對應的lastIndexOf(...)方法:表示從當前字串的尾部開始查詢;

boolean contains(CharSequence s)
當且僅當此字串包含指定的 char 值序列s時,返回 true。

我們上下程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String s1 = new String("asdfghjk");
 6         System.out.println(s1.indexOf('s'));
 7         System.out.println(s1.indexOf("fg"));
 8         System.out.println(s1.indexOf('h', 2));
 9         System.out.println(s1.indexOf("jk", 4));
10         System.out.println(s1.lastIndexOf('j'));
11         //System.out.println(s1.contains('sd'));// Invalid character constant
12         System.out.println(s1.contains("df"));
13         System.out.println(s1.contains("dfh"));
14         System.out.println(s1.contains("DF"));
15         System.out.println(s1.contains("df1"));
16         
17         
18     }
19 }

執行結果:

1
3
5
6
6
true
false
false
false

4.String類常用的方法三:
char[] toCharArray()
將此字串轉換為一個新的字元陣列。

int length()
返回此字串的長度。

boolean isEmpty()
當且僅當 length() 為 0 時返回 true。

String replace(char oldChar, char newChar)
返回一個新的字串,它是通過用 newChar 替換此字串中出現的所有 oldChar 得到的。

boolean startsWith(String prefix)
測試此字串是否以指定的字首開始。

String substring(int beginIndex)
返回一個新的字串,它是此字串的一個子字串。

String substring(int beginIndex, int endIndex)
返回一個新字串,它是此字串的一個子字串。

String toLowerCase()
將當前字串轉換為小寫形式,並將其返回

String toUpperCase()
將當前字串轉換為大寫形式,並將其返回

String trim()
去掉字串的前後空格,並將其返回

我們上下程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String s1 = new String("asdfghjk ");
 6         String s2 = new String();
 7         char[] arr = s1.toCharArray();
 8         System.out.println(arr);
 9         System.out.println(arr[1]);
10         System.out.println(s1.length());
11         System.out.println(s1.isEmpty());
12         System.out.println(s2.isEmpty());
13         System.out.println(s1.replace('d', 'v'));
14         System.out.println(s1.replace("gh","bnm"));
15         System.out.println(s1.startsWith("as"));
16         System.out.println(s1.substring(3));
17         System.out.println(s1.substring(2, 5));
18         System.out.println(s1.toUpperCase());
19         System.out.println(s1.trim());
20         
21         
22     }
23 }

執行結果:

asdfghjk
s
9
false
true
asvfghjk
asdfbnmjk
true
fghjk
dfg
ASDFGHJK
asdfghjk

二、java.lang.StringBuffer

StringBuffer類提供了String類不支援的新增,插入,修改,刪除之類的操作。總之,若相對字串進行操作,那麼請使用StringBuffer類

1. StringBuffer類常用的建構函式

StringBuffer()
構造一個其中不帶字元的字串緩衝區,初始容量(預設初始長度)為 16 個字元。

StringBuffer(int length)
構造一個不帶字元,但具有指定初始容量的字串緩衝區。

StringBuffer(String str)
構造一個字串緩衝區,並將其內容初始化為指定的字串內容,其長度為str長度+16個字元。

2.StringBuffer類常用的方法

append(資料型別 變數)
將引數的值轉換成字串,再新增到當前字串尾,然後將其返回

delete(int start,int end)
在當前字串中,刪除從下標start開始到下標end-1的字元,然後返回

deleteCharAt(int index)
刪除當前字串下標為index的字元,然後返回

insert(int offset,資料型別 變數)
將引數的值轉換成字串,並插入到當前字串下標為offset的位置處


replace(int start,int end,String str)
將字串從下標start開始至下標end-1之間的字串替換為str字串

reverse()
將字串反轉

charAt(int index),length(),substring(int start),substring(int start, int end)
這幾個方法和String類對應的方法功能相同

我們上下程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         StringBuffer sm = new StringBuffer();
 6         sm.append("1234");
 7         sm.append(false);
 8         sm.append(1110);
 9         System.out.println(sm);
10         
11         sm.delete(1, 3);
12         System.out.println(sm);
13         
14         sm.deleteCharAt(4);
15         System.out.println(sm);
16         
17         sm.insert(5, "vvcx");
18         System.out.println(sm);
19         
20         System.out.println(sm.reverse());
21         
22         
23     }
24 }

執行結果:

1234false1110
14false1110
14fase1110
14fasvvcxe1110
0111excvvsaf41

三、java.lang.Math類

Math類無法建立物件,其所有成員皆為靜態成員。
Math類常用方法:
static double ceil(double a)
返回一個大於或等於a的最小雙精度實數

static double floor(double a)
返回一個小於或等於a的最大雙精度實數

static double rint(double a)
返回最靠近a的雙精度實數

static double pow(double a,double b)
返回a的b次方

static int round(float a)
static long round(double a)
將a四捨五入後返回

static double random()
返回大於等於0且小於1的隨機數

abs(資料型別 a)

返回a的絕對值

max(資料型別 a,資料型別 b)

返回a,b中的較大者

min(資料型別 a,資料型別 b)

返回a,b中的較小者

上下程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 public class String2 {
 4     public static void main(String[] args) {
 5         System.out.println(Math.ceil(3.6));
 6         System.out.println(Math.ceil(-3.8));
 7         System.out.println(Math.floor(4.8));
 8         System.out.println(Math.floor(-2.5));
 9         
10         System.out.println(Math.rint(5.6));
11         System.out.println(Math.rint(-5.6));
12 
13         System.out.println(Math.pow(2,3));
14         
15         System.out.println(Math.round(1.25f));
16         System.out.println(Math.round(2.56));
17         
18         System.out.println(Math.random());
19         System.out.println(Math.random());
20             
21     }
22 }

執行結果:

4.0
-3.0
4.0
-3.0
6.0
-6.0
8.0
1
3
0.38971688391775905
0.8850603786760766

四、java.lang.Random類
Random類提供了產生多種形式隨機數的功能。雖然前面學過的Math類中的random()能產生隨機數,但它只能產生0.0-1.0之間的隨機數。工作上,若需要大量的不同形式的隨機數,便可用Random類。
Random類常用的方法:

boolean nextBoolean()
返回true或false中的一個

double nextDouble()
返回0.0~1.0之間的double小數

float nextFloat()
返回0.0~1.0之間的float小數

int nextInt()
返回int型整數

int nextInt(int n)
返回0到n-1之間的整數

long nextLong()
返回long型整數

直接上下程式碼:

 1 package com.learn.chap04.sec05;
 2 import java.util.Random;
 3 public class String2 {
 4     
 5     public static void main(String[] args) {
 6         Random rnd = new Random();
 7         String[] str = {"紅桃1","紅桃2","紅桃3","紅桃4","紅桃5","紅桃6"};
 8         for (int i = 0; i < 5; i++) {
 9             int m = rnd.nextInt(6);
10             System.out.println(str[m]);
11         }
12     }
13 }

執行結果:

紅桃6
紅桃6
紅桃1
紅桃3
紅桃1

五、java.util.Arrays類
  Arrays類提供了陣列整理,比較和檢索功能。它和Math一樣無法建立其物件,它的所以方法都是靜態方法。
  常用的方法:
  int binarySearch(陣列,key)
  對key值進行搜尋,並返回key所在位置

  boolean equals(陣列1,陣列2)
  比較兩個陣列,若兩個陣列元素均相同,則返回true,否則返回false

  void sort(陣列)
  對給定的陣列進行升序排序

上下程式碼:

 1 package com.learn.chap04.sec05;
 2 import java.util.Arrays;
 3 
 4 public class String2 {
 5     
 6     public static void main(String[] args) {
 7         int[] a = new int[]{51,23,45,68,78,93,36,29};
 8         int[] b = new int[]{51,23,45,68,78,93,36,29};
 9         int[] c = new int[]{51,23,45,68,78,93};
10         int[] d = a; // 傳址引用
11         Arrays.sort(a);
12         Arrays.sort(b);
13         for (int i = 0; i < a.length; i++) {
14             System.out.print(a[i]+" ");
15         }
16         System.out.println();
17         for (int i = 0; i < d.length; i++) {
18             System.out.print(d[i]+" ");
19         }
20         System.out.println();
21         System.out.println("36所在的位置:"+Arrays.binarySearch(a,36));
22         System.out.println("38所在的位置:"+Arrays.binarySearch(a,38));
23         
24         System.out.println("a與b是否相同:"+Arrays.equals(a, b));
25         System.out.println("a與c是否相同:"+Arrays.equals(a, c));
26         System.out.println("a與d是否相同:"+Arrays.equals(a, d));
27     
28     }
29 }

執行結果:

23 29 36 45 51 68 78 93
23 29 36 45 51 68 78 93
36所在的位置:2
38所在的位置:-4
a與b是否相同:true
a與c是否相同:false
a與d是否相同:true

六、java.util.StringTokenizer類
StringTokenizer類提供了將單詞從字串中分離出來的功能。各個單詞依據分隔符被分成一個個token.
  常用的構造方法:
  public StringTokenizer(String str)
  使用指定的字串建立物件

  public StringTokenizer(String str,String delim)
  使用指定的字串str和指定的字串分隔符delim,建立物件

  常用的方法:
  int countTokens()
  返回token的個數

  boolean hasMoreElements()
  boolean hasMoreTokens()
  若仍存在token,則返回true,負責返回false

  Object nextElement()
  String nextToken()
  返回下一個token

直接上程式碼:

 1 package com.learn.chap04.sec05;
 2 import java.util.StringTokenizer;
 3 public class String2 {
 4     public static void main(String[] args) {
 5         String str = new String("Thinking Java Programming with you ");
 6         StringTokenizer stoken = new StringTokenizer(str);
 7         System.out.println(stoken.countTokens());
 8         for (int i = 1; stoken.hasMoreElements(); i++) {
 9             System.out.println("第"+i+"個token:"+stoken.nextToken());
10         }
11     }
12 }

執行結果:

5
第1個token:Thinking
第2個token:Java
第3個token:Programming
第4個token:with
第5個token:you

七、java日期處理類
主要使用Date類Calendar類SimpleDateFormat類

直接上程式碼:

 1 package com.learn.chap04.sec05;
 2 
 3 import java.util.Date;
 4 
 5 public class TestDate {
 6     public static void main(String[] args) {
 7         Date date = new Date(); //若提示錯誤提示The constructor Date() is undefined,原因是引進的是import java.sql.Date,其實應該是import java.util.Date
 8         System.out.println("當前時間:"+date);
 9     }
10 }

執行結果:

當前時間:Sat Oct 22 18:35:14 CST 2016

 1 package com.learn.chap04.sec05;
 2 
 3 import java.util.Calendar;
 4 
 5 public class TestCalendar {
 6     
 7     public static void main(String[] args) {
 8         Calendar c = Calendar.getInstance();
 9         System.out.println(c.get(Calendar.YEAR));
10         System.out.println(c.get(Calendar.MONTH)+1);
11         System.out.println("現在是:"+c.get(Calendar.YEAR)+"年"
12         +(c.get(Calendar.MONTH)+1)+"月"
13         +c.get(Calendar.DAY_OF_MONTH)+"日"
14         +c.get(Calendar.HOUR_OF_DAY)+"時"
15         +c.get(Calendar.MINUTE)+"分"
16         +c.get(Calendar.SECOND)+"秒");
17         
18         final char[] week = {'日','一','二','三','四','五','六'};
19         int week_num = c.get(Calendar.DAY_OF_WEEK)-1;
20         System.out.println("今天是星期"+week[week_num]);
21     }
22 }

執行結果:

2016
10
現在是:2016年10月22日18時36分56秒
今天是星期六

 1 package com.learn.chap04.sec05;
 2 
 3 
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 
 8 public class TestSimpleDateFormat {
 9     /**    
10      * 將日期物件格式為指定格式的日期字串
11      * @return
12      */
13     public static String formatDate(Date date,String format){
14         String result = "";
15         SimpleDateFormat sm = new SimpleDateFormat(format);
16         if(date != null){
17             result = sm.format(date);
18         }
19         return result;
20     }
21     
22     /**
23      * 將日期字串轉換成日期物件
24      * @return
25      * @throws ParseException 
26      */
27     public static Date formatToDate(String dateStr,String format) throws ParseException{
28         SimpleDateFormat sm = new SimpleDateFormat(format);
29         return sm.parse(dateStr);
30     }
31     
32     public static void main(String[] args) throws ParseException {
33         Date date = new Date();
34         SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
35         System.out.println(sm.format(date));
36         
37         // 下面是呼叫封裝方法實現
38         System.out.println(formatDate(date,"yyyy-MM-dd"));
39         
40         String date1 = "2016-10-22 18:18:35";
41         Date    da   =  formatToDate(date1,"yyyy-MM-dd"); // 將日期字串轉換成日期物件
42         System.out.println(formatDate(da,"yyyy-MM-dd")); // 將日期物件格式為指定格式的日期字串
43         System.out.println(formatDate(da,"yyyy-MM-dd HH:mm:ss"));
44     }
45     
46 }

執行結果:

2016-10-22 18:38:50
2016-10-22
2016-10-22
2016-10-22 00:00:00