自定義異常,包裝類,String

1.自定義異常
作用:就是爲了能夠在顯示異常信息時,以中文的方式顯示。
使用:
自定義一個類讓當前類繼承自異常父類或子類,然後重寫父類的
構造方法,這就是一個自定義異常。

示例1:

/**
 * @author 
 * 自定義異常
 */
public class MyException extends RuntimeException{
public MyException() {
super();
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}


public MyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public MyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}

示例2:

/**
 * @author 
 * 自定義異常類  示例
 */
public class Test1 {
public static void main(String[] args) {
Test1 t=new Test1();
try{
t.display(0);
}catch(MyException ce){
ce.printStackTrace();
}
System.out.println("ok");
}
public void display(int num)throws MyException{
if(num==0){
throw new MyException("除數不能爲零");
}else{
System.out.println(10/0);
}
}
}

2.包裝類
java中所有的基本數據類型都有對應的包裝類
byte---- Byte
short----Short
int      Integer
char     Character
long     Long
float    Float
double   Double
boolean  Boolean
通過包裝類能夠更加靈活的實現基本數據類型之間的轉換,以及和其它
數據類型之間的轉換。

裝箱:從基本數據類型到所對應的包裝類的過程
拆箱:從包裝類到所對應的基本數據類型的過程
注意:裝箱和拆箱是JDK5.0以後新增的特性。

示例:

public class Test3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Integer對象
Integer num1=new Integer(10);
System.out.println(num1);
System.out.println(num1.intValue());
System.out.println(num1.longValue());
System.out.println(num1.doubleValue());
System.out.println(num1.floatValue());
System.out.println(num1.byteValue());
System.out.println(num1.toString()+10);
Integer num2=new Integer("123");
System.out.println(num2+1);
String str="456";
//轉換成int類型
int num3=Integer.parseInt(str);
System.out.println(num3+1);
//Character
System.out.println(Character.isDigit('c'));
System.out.println(Character.isLetter('a'));
System.out.println(Character.isLowerCase('A'));
System.out.println(Character.isUpperCase('A'));
//裝箱
int num4=10;
Integer i=num4;
System.out.println(i);
//拆箱
Double d=new Double(20.2);
double d2=d;
System.out.println(d2);
}
}


3.String類
由多個字符組成的序列就是字符串。
注意:在Java中字符串一定要使用雙引號。
特點:
1.String是一個不可變的字符序列,也就是說String 這個類是一個final修飾的類。
2.使用String類是,需要注意對象的創建;字符串是一個特殊的類使用的過程中可以對String對象直接賦值;如果通過new String("字符串")的形式創建字符串對象,會產生兩個隊形,一個對象是構造方法中的參數,一個構造方法參數對象的副本。
3.String採用的Unicode國際統一編碼。
4.字符串不可變的原因就是通過字符串池的原理實現的。

字符串池原理:在同一個項目中的所有字符串,實際上都會保存到同一個字符串池中,每聲明一個字符串對象,都會和字符串池中已經存在的字符串進行比較,如果字符串池中已經存在,則直接引用已存在的字符串的內存地址;否則,把字符串存入字符串池中。

示例:

public class Test4 {
public static void main(String[] args) {
String str="abc";
str="456";
System.out.println(str.length());
        String s1 = "abc中文";
        String s2 = "abc中文";
        String s3 = "abc";
        System.out.println(s1 == s2); // ? 
        System.out.println(s1 == s3); // ? 
        System.out.println(s1.equals(s2)); // ? 
        System.out.println(s1.equals(s3)); // ?       
        String ss1 = new String("abc中文");
        String ss2 = new String("abc中文");
        String ss3 = new String("abc");
        System.out.println(ss1 == ss2); // ?
        System.out.println(ss1 == ss3); // ? 
        System.out.println(ss1.equals(ss2)); // ?
        System.out.println(ss1.equals(ss3)); // ?     
        System.out.println("abc".equals("ABC"));   
        System.out.println("ABC".equalsIgnoreCase("abc"));
        System.out.println("abc".compareTo("ab"));
        System.out.println("abc".compareTo("ade"));    
        System.out.println("abc".compareTo("Abc"));    
        System.out.println("abcdefg".startsWith("a"));
        System.out.println("abc".endsWith("c"));
}
}

4.String常用方法
length()判斷字符串的長度
==:是用來判斷兩個字符串是否指向同一個內存地址.
equals()方法時用來判斷兩個字符串的內容是否一致。

compareTo()的返回值是整型,它是先比較對應字符的大小(ASCII碼順序),如果第一個字符和參數的第一個字符不等,結束比較,返回他們之間的 
差值,如果第一個字符和參數的第一個字符相等,則以第二個字符和參數的第二個字符做比較,以此類推,直至比較的字符或被比較的字符有一方 
全比較完,這時就比較字符的長度. 
例: 
String s1 = "abc"; 
String s2 = "abcd"; 
String s3 = "abcdfg"; 
String s4 = "1bcdfg"; 
String s5 = "cdfg"; 
System.out.println( s1.compareTo(s2) ); // -1 (前面相等,s1長度小1) 
System.out.println( s1.compareTo(s3) ); // -3 (前面相等,s1長度小3) 
System.out.println( s1.compareTo(s4) ); // 48 ("a"的ASCII碼是97,"1"的的ASCII碼是49,所以返回48) 
System.out.println( s1.compareTo(s5) ); // -2 ("a"的ASCII碼是97,"c"的ASCII碼是99,所以返回-2) 

示例1:

/**
 * @author 
 * 字符串搜索相關的方法
 * 驗證郵箱格式是否正確,規則.com||.cn 在@符號的後面,符合這一規則的就是
 * 合法的郵箱。
 */
public class Test5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("abcaaa".indexOf("aaa"));
System.out.println("zhangsan".lastIndexOf('s'));
System.out.println("zhangsansanzhangsan".lastIndexOf("san"));
System.out.println("zhangsan".charAt(2));
}
public boolean display(String email){
boolean flag=false;
if(email.indexOf("@")<email.indexOf(".com")){
System.out.println("ok");
}else{

}
return flag;
}
}

示例2:

/**
 * @author 
 * 字符串修改相關的方法
 */
public class Test6 {
public static void main(String[] args) {
String str="zhangsanliswangwu";
System.out.println(str.substring(5));
System.out.println(str.substring(0, 6));
System.out.println(str.concat("tianqi"));
System.out.println("zhangsansansan".replace('a', 'c'));
String str2="    lisi   ";
System.out.println(str2.trim());
System.out.println("abc".toUpperCase());
System.out.println("HELLO".toLowerCase());
System.out.println(String.valueOf(10));
}
}


1. 使用JDK提供的一些很常用的類,主要通過閱讀JavaSE API。
2. 基本數據類型的包裝類:
   1) JDK爲每一種基本數據類型都提供了一個對應的包裝類。  .xxxValue();
   byte  --> java.lang.Byte
   short --> java.lang.Short
   int   --> java.lang.Integer         ☆
   long  --> java.lang.Long
   char  --> java.lang.Character       ☆
   float --> java.lang.Float
   double--> java.lang.Double
   boolean-> java.lang.Boolean
   2) 掌握各種基本類型數據和包裝類之間的相互轉換,與字符串之間的相互轉換。
   3) JDK5.0中針對基本數據類型提供了一個新語法:自動裝箱和自動拆箱。
      自動裝箱:把基本類型的數據直接當作對應的包裝類對象來使用。

      自動拆箱:把包裝類對象直接當作對應的基本類型數據。


3.字符串相關類
 1) java.lang.String: 代表不可變的字符序列。特殊的引用數據類型。
     a) String str = "abc";  //最常用
        String str2 = new String("abc");
     b) 字符串可以使用“+”來連接:String str3 = "abc" + "中國";
        也可以用“+”跟其它類型數據進行連接:String str4 = "abc" + 12.345;
     c) String類有一個方法length()可以獲取它的長度。 
        String str5 = "salkdf";
        str5.length();    // "salkdf".length();
     d) 字符串的比較
       ① == : 比較兩個字符串的內存地址。  //用得少
       ② boolean equals(Object object): 比較的是兩個字符串的內容。最常用的方法。
       ③ boolean equalsIgnoreCase(): 忽略大小寫比較兩個字符串的內容。
       ④ int compareTo(String str2): 比較兩個字符串的字典順序。
                                      如果相等,返回0
                                      如果在參數字符串位置之前,返回負數。
                                      如果在參數字符串位置之後,返回正數。 
       ⑤ int compareToIgnoreCase(String str2): 忽略大小寫比較兩個字符串的字典順序。
       ⑥ boolean startsWith(String str): 是否以參數字符串開頭

       ⑦ boolean endsWith(String str): 是否以參數字符串結尾

    e) 搜索字符串
       ① int indexOf(int ch): 搜索指定字符在本串中的索引(從0開始)
       ② int indexOf(String str): 搜索指定字符串在本串中的索引(從0開始)
       ③ int lastIndexOf(int ch)
       ④ int lastIndexOf(String str)

    f) 提取子字符串
       ① char charAt(int index): 提取指定索引處的那個字符。
       ② String substring(int beginIndex):提取從指定索引處到結尾的子串。
       ③ String substring(int beginIndex, int endIndex):提取從 beginindex開始直到 endindex(不包括此位置)之間的這部分字符串
       ④ String concat(String str):跟“+”的功能一樣。
       ⑤ String replace(char oldChar,char newChar):返回一個新的字符串,它是通過用newChar 替換此字符串中出現的所有oldChar而生成的。 
       ⑥ String trim(); 去掉字符串的前後空格。
    g) 轉大小寫
       ① String toUpperCase(); 轉成大寫
       ② String toLowerCase(); 轉成小寫
    h) 其它類型轉換成字符串: 
       static String valueOf(…)可以將基本類型數據、Object類型轉換爲字符串。
    i) 與正則表達式相關的方法:
       ① String[] split(String regex); 根據給定正則表達式的匹配拆分此字符串
       ② String replaceAll(String regex, String replacement)使用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串.
       ③ public boolean matches(String regex)告知此字符串是否匹配給定的正則表達式

    j) 如果要對字符串內容進行頻繁的更改時,不建議使用“+”,而應該用StringBuffer或StringBuider類

示例1:

/**
 * @author
 * 字符串修改相關的方法
 */
public class Test6 {
public static void main(String[] args) {
String str="zhangsanliswangwu";
System.out.println(str.substring(5));
System.out.println(str.substring(0, 6));
System.out.println(str.concat("tianqi"));
System.out.println("zhangsansansan".replace('a', 'c'));
String str2="    lisi   ";
System.out.println(str2.trim());
System.out.println("abc".toUpperCase());
System.out.println("HELLO".toLowerCase());
System.out.println(String.valueOf(10));
}
}

示例2:

/**
 * @author 
 * split 方法
 */
public class Test7 {
public static void main(String[] args) {
String str="hello-world-ni-hao";
String[]s=str.split("-");
for(String a:s){
System.out.println(a);
}
}
}

示例3:

/**
 * @author 
 *編寫一個java方法,用來統計所給字符串中大寫英文字母的個數,
 *小寫英文字母的個數以及數字的個數再以及特殊字符的個數。
 */
public class Test8 {
public static void main(String[] args) {
String str="AAKLDSJFewrqq@!$%^&*(asdfa89713461akshdf1234@#$%^";
//step1:如何獲取字符串中的每個字符
char[]c=str.toCharArray();
int count1=0;//大寫
int count2=0;//小寫
int count3=0;//數字
int count4=0;//特殊字符
for(int i=0;i<c.length;i++){
if(Character.isUpperCase(c[i])){
count1++;
}else if(Character.isLowerCase(c[i])){
count2++;
}else if(Character.isDigit(c[i])){
count3++;
}else{
count4++;
}
}
System.out.println("大寫:"+count1);
System.out.println("小寫:"+count2);
System.out.println("數字:"+count3);
System.out.println("特殊字符:"+count4);
}
}

示例4:

/**
 * @author 
 * 有一個字符串 String str="welcome to beijing";把該字符串中每個單詞的首字母改成大寫
 * 其它不變,輸出的結果應該是: Welcome To Beijing
 */
public class Test9 {
public static void main(String[] args) {
String str="welcome to beijing";
//step1:如何得到每個單詞
String[]s=str.split(" ");
for(int i=0;i<s.length;i++){
System.out.print(s[i].substring(0, 1).toUpperCase().concat(s[i].substring(1))+"\t");
}
}
}

示例5:

import static java.lang.Math.*;
/**
 * @author lw
 * Math類示例
 * -11.5
 */
public class Test10 {
public static void main(String[] args) {
System.out.println(PI);
System.out.println(round(-11.4));
System.out.println(random());
}
}

示例6:

import java.util.Random;
/**
 * @author 
 * Random 隨機數
 */
public class Test11 {
public static void main(String[] args) {
Random rd=new Random();
System.out.println(rd.nextInt(10));
System.out.println(rd.nextInt());
System.out.println(rd.nextBoolean());
Random rd2=new Random(10000000L);
Random rd3=new Random(10000000L);
System.out.println(rd2.nextInt());
System.out.println(rd3.nextInt());
}
}


作業:

/**
 * @author wx
 * 
 * 1. 編寫一個方法:
  public static int count(String source, String key));從source字符串中查找key字符串出現的次數。
比如:
String source = "String testStringte st testString testString test";
String key = "test";
那麼這個方法應該返回4。
 *
 */
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String source = "StringtestStringtesttestStringtestStringtestStringStringtesttest";
int c=count(source, "String");
System.out.println(c);
}

public static int count(String source, String key){
int index=source.indexOf(key, 0);
int c=0;
while(index!=-1){
c++;
index=source.indexOf(key, index+key.length());
}
return c;
}
}


2.編寫一個方法public String  initcap(String word);  把整句話的每個單詞的首字母改成大寫,其它不變。

/**
 * @author wx
 * 有一個字符串 String str="welcome to beijing";把該字符串中每個單詞的首字母改成大寫
 * 其它不變,輸出的結果應該是: Welcome To Beijing
 */
public class Test9 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="welcome to beijing";
//step1:如何得到每個單詞
String[]s=str.split(" ");
for(int i=0;i<s.length;i++){
System.out.print(s[i].substring(0, 1).toUpperCase().concat(s[i].substring(1))+"\t");
}
}
}

3.

import java.util.Random;

/**
 * @author wx
 * 編寫一個Java方法,生成5個不重複的英文小寫字母,並按字母順序排列好。
 */
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
display();
}

public static void display(){
Random rd=new Random();
char[]c=new char[5];
for(int i=0;i<c.length;i++){
char temp=(char)(rd.nextInt(26)+97);
boolean f=validate(c, temp);
if(f){
--i;
continue;
}else{
c[i]=temp;
}
}

for(char a:c){
System.out.println(a);
}
}

/**
* 判斷指定的數組中,是否已經存在指定的數據
* @param c
* @param a
* @return
*/
public static boolean validate(char[]c,char a){
boolean flag=false;
for(int i=0;i<c.length;i++){
if(c[i]==a){
flag=true;
break;
}

}
return flag;
}
}

4.

/**
 * @author wx
 *驗證給定的用戶名是否合法。合法用戶名的要求是:只能以英字母開頭,字符只能包括英文字母、數字和下劃線,長度必須在6-20位之間。
 */
public class Test3 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test3 t=new Test3();
boolean flag=t.display();
if(flag){
System.out.println("ok");
}else{
System.out.println("no ok");
}
}

public boolean display(){
boolean flag=false;
String name="Azhangsan_123";
if(name.length()>6&&name.length()<20){
char[]c=name.toCharArray();
if(Character.isLetter(c[0])){
for(int i=0;i<c.length;i++){
if(Character.isDigit(c[i])){
flag=true;
}else if(c[i]=='_'){
flag=true;
}else{
flag=false;
}
}
}else{
flag=false;
}
}
return flag;
}
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章