1. 程式人生 > 其它 >常用API&異常

常用API&異常

1.包裝類

1.1基本型別包裝類(記憶)

  • 基本型別包裝類的作用

    ​ 將基本資料型別封裝成物件的好處在於可以在物件中定義更多的功能方法操作該資料

    ​ 常用的操作之一:用於基本資料型別與字串之間的轉換

  • 基本型別對應的包裝類

    基本資料型別 包裝類
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double
    char Character
    boolean Boolean

1.2Integer類(應用)

  • Integer類概述

    ​ 包裝一個物件中的原始型別 int 的值

  • Integer類構造方法

    方法名 說明
    public Integer(int value) 根據 int 值建立 Integer 物件(過時)
    public Integer(String s) 根據 String 值建立 Integer 物件(過時)
    public static Integer valueOf(int i) 返回表示指定的 int 值的 Integer 例項
    public static Integer valueOf(String s) 返回一個儲存指定值的 Integer 物件 String
  • 示例程式碼

    public class IntegerDemo {
        public static void main(String[] args) {
            //public Integer(int value):根據 int 值建立 Integer 物件(過時)
            Integer i1 = new Integer(100);
            System.out.println(i1);
    
            //public Integer(String s):根據 String 值建立 Integer 物件(過時)
            Integer i2 = new Integer("100");
    //        Integer i2 = new Integer("abc"); //NumberFormatException
            System.out.println(i2);
            System.out.println("--------");
    
            //public static Integer valueOf(int i):返回表示指定的 int 值的 Integer 例項
            Integer i3 = Integer.valueOf(100);
            System.out.println(i3);
    
            //public static Integer valueOf(String s):返回一個儲存指定值的Integer物件 String
            Integer i4 = Integer.valueOf("100");
            System.out.println(i4);
        }
    }
    

1.3int和String型別的相互轉換(記憶)

  • int轉換為String

    • 轉換方式

      • 方式一:直接在數字後加一個空字串
      • 方式二:通過String類靜態方法valueOf()
    • 示例程式碼

      public class IntegerDemo {
          public static void main(String[] args) {
              //int --- String
              int number = 100;
              //方式1
              String s1 = number + "";
              System.out.println(s1);
              //方式2
              //public static String valueOf(int i)
              String s2 = String.valueOf(number);
              System.out.println(s2);
              System.out.println("--------");
          }
      }
      
  • String轉換為int

    • 轉換方式

      • 方式一:先將字串數字轉成Integer,再呼叫valueOf()方法
      • 方式二:通過Integer靜態方法parseInt()進行轉換
    • 示例程式碼

      public class IntegerDemo {
          public static void main(String[] args) {
              //String --- int
              String s = "100";
              //方式1:String --- Integer --- int
              Integer i = Integer.valueOf(s);
              //public int intValue()
              int x = i.intValue();
              System.out.println(x);
              //方式2
              //public static int parseInt(String s)
              int y = Integer.parseInt(s);
              System.out.println(y);
          }
      }
      

1.4字串資料排序案例(應用)

  • 案例需求

    ​ 有一個字串:“91 27 46 38 50”,請寫程式實現最終輸出結果是:“27 38 46 50 91”

  • 程式碼實現

    public class IntegerTest {
        public static void main(String[] args) {
            //定義一個字串
            String s = "91 27 46 38 50";
    
            //把字串中的數字資料儲存到一個int型別的陣列中
            String[] strArray = s.split(" ");
    //        for(int i=0; i<strArray.length; i++) {
    //            System.out.println(strArray[i]);
    //        }
    
            //定義一個int陣列,把 String[] 陣列中的每一個元素儲存到 int 陣列中
            int[] arr = new int[strArray.length];
            for(int i=0; i<arr.length; i++) {
                arr[i] = Integer.parseInt(strArray[i]);
            }
    
            //對 int 陣列進行排序
            Arrays.sort(arr);
    
            //把排序後的int陣列中的元素進行拼接得到一個字串,這裡拼接採用StringBuilder來實現
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<arr.length; i++) {
                if(i == arr.length - 1) {
                    sb.append(arr[i]);
                } else {
                    sb.append(arr[i]).append(" ");
                }
            }
            String result = sb.toString();
    
            //輸出結果
            System.out.println(result);
        }
    }
    

1.5自動拆箱和自動裝箱(理解)

  • 自動裝箱

    ​ 把基本資料型別轉換為對應的包裝類型別

  • 自動拆箱

    ​ 把包裝類型別轉換為對應的基本資料型別

  • 示例程式碼

    Integer i = 100;  // 自動裝箱
    i += 200;         // i = i + 200;  i + 200 自動拆箱;i = i + 200; 是自動裝箱
    

2.時間日期類

2.1Date類(應用)

  • Date類概述

    ​ Date 代表了一個特定的時間,精確到毫秒

  • Date類構造方法

    方法名 說明
    public Date() 分配一個 Date物件,並初始化,以便它代表它被分配的時間,精確到毫秒
    public Date(long date) 分配一個 Date物件,並將其初始化為表示從標準基準時間起指定的毫秒數
  • 示例程式碼

    public class DateDemo01 {
        public static void main(String[] args) {
            //public Date():分配一個 Date物件,並初始化,以便它代表它被分配的時間,精確到毫秒
            Date d1 = new Date();
            System.out.println(d1);
    
            //public Date(long date):分配一個 Date物件,並將其初始化為表示從標準基準時間起指定的毫秒數
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);
        }
    }
    

2.2Date類常用方法(應用)

  • 常用方法

    方法名 說明
    public long getTime() 獲取的是日期物件從1970年1月1日 00:00:00到現在的毫秒值
    public void setTime(long time) 設定時間,給的是毫秒值
  • 示例程式碼

    public class DateDemo02 {
        public static void main(String[] args) {
            //建立日期物件
            Date d = new Date();
    
            //public long getTime():獲取的是日期物件從1970年1月1日 00:00:00到現在的毫秒值
    //        System.out.println(d.getTime());
    //        System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");
    
            //public void setTime(long time):設定時間,給的是毫秒值
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

2.3SimpleDateFormat類(應用)

  • SimpleDateFormat類概述

    ​ SimpleDateFormat是一個具體的類,用於以區域設定敏感的方式格式化和解析日期。

    ​ 我們重點學習日期格式化和解析

  • SimpleDateFormat類構造方法

    方法名 說明
    public SimpleDateFormat() 構造一個SimpleDateFormat,使用預設模式和日期格式
    public SimpleDateFormat(String pattern) 構造一個SimpleDateFormat使用給定的模式和預設的日期格式
  • SimpleDateFormat類的常用方法

    • 格式化(從Date到String)
      • public final String format(Date date):將日期格式化成日期/時間字串
    • 解析(從String到Date)
      • public Date parse(String source):從給定字串的開始解析文字以生成日期
  • 示例程式碼

    public class SimpleDateFormatDemo {
        public static void main(String[] args) throws ParseException {
            //格式化:從 Date 到 String
            Date d = new Date();
    //        SimpleDateFormat sdf = new SimpleDateFormat();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
    
            //從 String 到 Date
            String ss = "2048-08-09 11:11:11";
            //ParseException
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

2.4日期工具類案例(應用)

  • 案例需求

    ​ 定義一個日期工具類(DateUtils),包含兩個方法:把日期轉換為指定格式的字串;把字串解析為指定格式的日期,然後定義一個測試類(DateDemo),測試日期工具類的方法

  • 程式碼實現

    • 工具類
    public class DateUtils {
        private DateUtils() {}
    
        /*
            把日期轉為指定格式的字串
            返回值型別:String
            引數:Date date, String format
         */
        public static String dateToString(Date date, String format) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            String s = sdf.format(date);
            return s;
        }
    
    
        /*
            把字串解析為指定格式的日期
            返回值型別:Date
            引數:String s, String format
         */
        public static Date stringToDate(String s, String format) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date d = sdf.parse(s);
            return d;
        }
    
    }
    
    • 測試類
    public class DateDemo {
        public static void main(String[] args) throws ParseException {
            //建立日期物件
            Date d = new Date();
    
            String s1 = DateUtils.dateToString(d, "yyyy年MM月dd日 HH:mm:ss");
            System.out.println(s1);
    
            String s2 = DateUtils.dateToString(d, "yyyy年MM月dd日");
            System.out.println(s2);
    
            String s3 = DateUtils.dateToString(d, "HH:mm:ss");
            System.out.println(s3);
            System.out.println("--------");
    
            String s = "2048-08-09 12:12:12";
            Date dd = DateUtils.stringToDate(s, "yyyy-MM-dd HH:mm:ss");
            System.out.println(dd);
        }
    }
    

2.5Calendar類(應用)

  • Calendar類概述

    ​ Calendar 為特定瞬間與一組日曆欄位之間的轉換提供了一些方法,併為操作日曆欄位提供了一些方法

    ​ Calendar 提供了一個類方法 getInstance 用於獲取這種型別的一般有用的物件。

    ​ 該方法返回一個Calendar 物件。

    ​ 其日曆欄位已使用當前日期和時間初始化:Calendar rightNow = Calendar.getInstance();

  • Calendar類常用方法

    方法名 說明
    public int get(int field) 返回給定日曆欄位的值
    public abstract void add(int field, int amount) 根據日曆的規則,將指定的時間量新增或減去給定的日曆欄位
    public final void set(int year,int month,int date) 設定當前日曆的年月日
  • 示例程式碼

    public class CalendarDemo {
        public static void main(String[] args) {
            //獲取日曆類物件
            Calendar c = Calendar.getInstance();
    
            //public int get(int field):返回給定日曆欄位的值
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH) + 1;
            int date = c.get(Calendar.DATE);
            System.out.println(year + "年" + month + "月" + date + "日");
    
            //public abstract void add(int field, int amount):根據日曆的規則,將指定的時間量新增或減去給定的日曆欄位
            //需求1:3年前的今天
    //        c.add(Calendar.YEAR,-3);
    //        year = c.get(Calendar.YEAR);
    //        month = c.get(Calendar.MONTH) + 1;
    //        date = c.get(Calendar.DATE);
    //        System.out.println(year + "年" + month + "月" + date + "日");
    
            //需求2:10年後的10天前
    //        c.add(Calendar.YEAR,10);
    //        c.add(Calendar.DATE,-10);
    //        year = c.get(Calendar.YEAR);
    //        month = c.get(Calendar.MONTH) + 1;
    //        date = c.get(Calendar.DATE);
    //        System.out.println(year + "年" + month + "月" + date + "日");
    
            //public final void set(int year,int month,int date):設定當前日曆的年月日
            c.set(2050,10,10);
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH) + 1;
            date = c.get(Calendar.DATE);
            System.out.println(year + "年" + month + "月" + date + "日");
    
        }
    }
    

2.6二月天案例(應用)

  • 案例需求

    ​ 獲取任意一年的二月有多少天

  • 程式碼實現

    public class CalendarTest {
        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日往前推一天,就是2月的最後一天
            c.add(Calendar.DATE, -1);
    
            //獲取這一天輸出即可
            int date = c.get(Calendar.DATE);
            System.out.println(year + "年的2月份有" + date + "天");
        }
    }
    

3.異常

3.1異常(記憶)

  • 異常的概述

    ​ 異常就是程式出現了不正常的情況

  • 異常的體系結構

3.2JVM預設處理異常的方式(理解)

  • 如果程式出現了問題,我們沒有做任何處理,最終JVM 會做預設的處理,處理方式有如下兩個步驟:

  • 把異常的名稱,錯誤原因及異常出現的位置等資訊輸出在了控制檯

  • 程式停止執行

3.3try-catch方式處理異常(應用)

  • 定義格式

    try {
    	可能出現異常的程式碼;
    } catch(異常類名 變數名) {
    	異常的處理程式碼;
    }
    
  • 執行流程

    • 程式從 try 裡面的程式碼開始執行
    • 出現異常,就會跳轉到對應的 catch 裡面去執行
    • 執行完畢之後,程式還可以繼續往下執行
  • 示例程式碼

    public class ExceptionDemo01 {
        public static void main(String[] args) {
            System.out.println("開始");
            method();
            System.out.println("結束");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]);
                System.out.println("這裡能夠訪問到嗎");
            } catch (ArrayIndexOutOfBoundsException e) {
    //            System.out.println("你訪問的陣列索引不存在,請回去修改為正確的索引");
                e.printStackTrace();
            }
        }
    }
    

3.4Throwable成員方法(應用)

  • 常用方法

    方法名 說明
    public String getMessage() 返回此 throwable 的詳細訊息字串
    public String toString() 返回此可丟擲的簡短描述
    public void printStackTrace() 把異常的錯誤資訊輸出在控制檯
  • 示例程式碼

    public class ExceptionDemo02 {
        public static void main(String[] args) {
            System.out.println("開始");
            method();
            System.out.println("結束");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
                System.out.println("這裡能夠訪問到嗎");
            } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
    //            e.printStackTrace();
    
                //public String getMessage():返回此 throwable 的詳細訊息字串
    //            System.out.println(e.getMessage());
                //Index 3 out of bounds for length 3
    
                //public String toString():返回此可丟擲的簡短描述
    //            System.out.println(e.toString());
                //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    
                //public void printStackTrace():把異常的錯誤資訊輸出在控制檯
                e.printStackTrace();
    //            java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    //            at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
    //            at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
    
            }
        }
    }
    

3.5編譯時異常和執行時異常的區別(記憶)

  • 編譯時異常

    • 都是Exception類及其子類
    • 必須顯示處理,否則程式就會發生錯誤,無法通過編譯
  • 執行時異常

    • 都是RuntimeException類及其子類
    • 無需顯示處理,也可以和編譯時異常一樣處理

3.6throws方式處理異常(應用)

  • 定義格式

    public void 方法() throws 異常類名 {
        
    }
    
  • 示例程式碼

    public class ExceptionDemo {
        public static void main(String[] args) {
            System.out.println("開始");
    //        method();
            try {
                method2();
            }catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("結束");
        }
    
        //編譯時異常
        public static void method2() throws ParseException {
            String s = "2048-08-09";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse(s);
            System.out.println(d);
        }
    
        //執行時異常
        public static void method() throws ArrayIndexOutOfBoundsException {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);
        }
    }
    
  • 注意事項

    • 這個throws格式是跟在方法的括號後面的
    • 編譯時異常必須要進行處理,兩種處理方案:try...catch …或者 throws,如果採用 throws 這種方案,將來誰呼叫誰處理
    • 執行時異常可以不處理,出現問題後,需要我們回來修改程式碼

3.7throws和throw的區別(記憶)

3.8自定義異常(應用)

  • 自定義異常類

    public class ScoreException extends Exception {
    
        public ScoreException() {}
    
        public ScoreException(String message) {
            super(message);
        }
    
    }
    
  • 老師類

    public class Teacher {
        public void checkScore(int score) throws ScoreException {
            if(score<0 || score>100) {
    //            throw new ScoreException();
                throw new ScoreException("你給的分數有誤,分數應該在0-100之間");
            } else {
                System.out.println("成績正常");
            }
        }
    }
    
  • 測試類

    public class Demo {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("請輸入分數:");
    
            int score = sc.nextInt();
    
            Teacher t = new Teacher();
            try {
                t.checkScore(score);
            } catch (ScoreException e) {
                e.printStackTrace();
            }
        }
    }