天天看點

常用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),測試日期工具類的方法

  • 代碼實作
    • 工具類
    • 測試類

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) 設定目前月曆的年月日
  • 示例代碼

2.6二月天案例(應用)

  • 案例需求

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

  • 代碼實作

3.異常

3.1異常(記憶)

  • 異常的概述

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

  • 異常的體系結構

    ​ [外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-WkLfoRQK-1628240972282)(img\01.png)]

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

  • 如果程式出現了問題,我們沒有做任何處理,最終JVM 會做預設的處理,處理方式有如下兩個步驟:
  • 把異常的名稱,錯誤原因及異常出現的位置等資訊輸出在了控制台
  • 程式停止執行

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

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

3.4Throwable成員方法(應用)

  • 常用方法
    方法名 說明
    public String getMessage() 傳回此 throwable 的詳細消息字元串
    public String toString() 傳回此可抛出的簡短描述
    public void printStackTrace() 把異常的錯誤資訊輸出在控制台
  • 示例代碼

3.5編譯時異常和運作時異常的差別(記憶)

  • 編譯時異常
    • 都是Exception類及其子類
    • 必須顯示處理,否則程式就會發生錯誤,無法通過編譯
  • 運作時異常
    • 都是RuntimeException類及其子類
    • 無需顯示處理,也可以和編譯時異常一樣處理

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

  • 定義格式
  • 示例代碼
  • 注意事項
    • 這個throws格式是跟在方法的括号後面的
    • 編譯時異常必須要進行處理,兩種處理方案:try…catch …或者 throws,如果采用 throws 這種方案,将來誰調用誰處理
    • 運作時異常可以不處理,出現問題後,需要我們回來修改代碼

3.7throws和throw的差別(記憶)

[外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-lgrX8t35-1628240972284)(img\02.png)]

3.8自定義異常(應用)

  • 自定義異常類
  • 老師類
    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();
            }
        }
    }