java常用類和異常機制

自動拆裝箱

//測試自動拆裝箱
public class AutoboxAndUnbox {
    public static void main(String[] args) {
        //jdk5.0後,自動裝箱,編譯幫我們改進代碼:Integer a = new Integer("100");
        Integer a = 100;
        Integer b = 200;

        //int c = new Integer("1000");
        int c = new Integer(1000);  //自動拆箱,編譯器改進:new Integer(1000).intValue();

        Integer d = null;
        int e = d; //d.intValue(); 會拋出空指針異常(NullPointerException)

        Integer f = 1234;
        Integer f1 = 1234;
        System.out.println(f == f1);  //false
        System.out.println(f.equals(f1));  //true

        Integer g = 123;//[-128, 127]之間的數,仍然當做基本數據類型來處理
        Integer g1 = 123;
        System.out.println(g == g1);  //true
        System.out.println(g.equals(g1));  //true
    }
}

Date類

//測試Date類
public class DateTest {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d);  //打印當前時間

        //獲取從時間戳到此時此刻所經歷的毫秒數
        long t = System.currentTimeMillis();
        System.out.println(t);

        Date d2 = new Date(1000);
        System.out.println(d2.toGMTString()); //1 Jan 1970 00:00:01 GMT

        d2.setTime(24324324);

        System.out.println(d2.getTime());  //24324324

        System.out.println(d.getTime() < d2.getTime()); //false
    }
}

DateFormat類和SimpleDateFormat類

//測試DateFormat類和SimpleDateFormat類
public class DateFormatTest {
    public static void main(String[] args) {
        //DateFormat類是抽象類
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");//MM必須大寫

        Date d = new Date();
        String str = df.format(d); //將時間對象按照格式化字符串轉化爲字符串
        System.out.println(str);  //2016年11月30日 10:38:26

        String str2 = "1997-7-7";
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d2 = df2.parse(str2);//將字符串按照格式化字符串轉化爲時間對象
            System.out.println(d2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Calendar類和GregorianCalendar類

注意:
- 月份:1月用0表示,12月用11表示
- 星期:週日是1,週六是7

//測試Calendar類
public class CalendarTest {
    public static void main(String[] args) {
        //Calendar是抽象類
        Calendar c = new GregorianCalendar();
        c.set(2001, 1, 10, 12, 23, 34);
        Date d = c.getTime();
        System.out.println(d); //Sat Feb 10 12:23:34 CST 2001

        //測試日期計算
        c.add(Calendar.YEAR, 30); //加30年
        System.out.println(c);
    }
}

可視化日曆小程序

public class VisualCarlendar {
    public static void main(String[] args) throws Exception {
        System.out.println("請輸入日期(格式1970-01-01):");
        Scanner scanner = new Scanner(System.in);
        String inputStr = scanner.nextLine();       

        //將輸入的日期字符串轉化成爲日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date inputDate = df.parse(inputStr);

        //將日期放進Calendar類進行處理
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(inputDate);

        //記錄輸入的日期
        int date = calendar.get(Calendar.DATE);

        //確定當月的1號是星期幾
        calendar.set(Calendar.DATE, 1);
        int startDay = calendar.get(Calendar.DAY_OF_WEEK);

        //確定當月最大的天數是多少
        int endDay = calendar.getActualMaximum(Calendar.DATE);

        System.out.println("一\t二\t三\t四\t五\t六\t日");
        //打印空格
        for(int i = 0; i < startDay - 2; i++) {
            System.out.print("\t");
        }

        for(int i = 1; i <= endDay; i++) {
            //標記輸入的日期
            if(date == i) {
                System.out.print(i + "*\t");
            }else{
                System.out.print(i + "\t");
            }
            int temp = calendar.get(Calendar.DAY_OF_WEEK);
            //每到星期日換行
            if( temp == Calendar.SUNDAY) {
                System.out.println();
            }
            //每打印一次日期加一
            calendar.add(Calendar.DATE, 1);
        }
    }
}

異常處理類結構

需要程序員處理的異常是已檢異常
異常

帶資源的try語句

try(Scanner in = new Scanner(new FileInputStream("F:/DB/abc.txt")),PrintWriter out = new PrintWriter("out.txt")){
  while(in.hasNext()) {
    out.println(in.next().toUpperCase());
  }
}

1)、不論這個塊如何退出,in和out都會關閉
2)、帶資源的try語句自身也可以帶catch和finally字句,這些字句會在資源關閉後執行

分析堆棧跟蹤元素

public class StackTraceTest {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter n: ");
        int n = in.nextInt();
        factorial(n);
    }

    //求階乘
    public static int factorial(int n) {
        System.out.println("factorial(" + n + ");");
        Throwable t = new Throwable();
        StackTraceElement[] frames = t.getStackTrace();  //獲取所有堆棧信息,組成一個數組
        for(StackTraceElement f : frames) {
            System.out.println(f);
        }
        int r;
        if(n <= 1) {
            r = 1;
        }else{
            r = n * factorial(n - 1);
            System.out.println("return " + r);
        }
        return r;
    }
}

使用斷言

assert關鍵字有兩種用法
1)、assert條件
2)、assert條件:表達式
這兩種方式都會對條件進行檢測,如果結果爲false,就拋出一個AssertionError異常

debug常用快捷鍵

  • F5 單步跳入,遇到函數進入函數內部
  • F6 單步跳過,遇到函數不進入函數內部
  • F7 單步返回,由函數內部返回到調用處
  • F8 一直執行到下一個斷點

異常

異常處理的三種方式:
- try…catch…finally語句
- throws關鍵字(聲明異常:將異常交給調用者處理)
- throw關鍵字手動拋出異常
方法重寫中聲明異常的原則:
- 父類沒有聲明異常,那麼子類也不能聲明異常
- 子類不可拋出原有方法拋出異常類的父類或上層類
- 子類拋出的異常類型的數目不可以比原有方法拋出的還多
自定義異常:
從Exception類或它的子類派生一個子類即可

//自定義異常
public class MyException extends Exception{
    //自定義異常一般要兩個構造器:
    //一個空參構造器,一個是帶有詳細信息的構造器
    public MyException() {

    }

    public MyException(String message) {
        super(message);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章