1. 程式人生 > 其它 >Java學習第三十七天<面向物件習題><異常體系><五大執行異常><異常處理><異常習題>

Java學習第三十七天<面向物件習題><異常體系><五大執行異常><異常處理><異常習題>

面向物件習題

package chapter14;
​
public class Homework01 {
    public static void main(String[] args) {
        Car c = new Car();
        Car c1 = new Car(100);
        System.out.println(c);//9 red
        System.out.println(c1);//100 red
    }
}
class Car{
    double price=10;
    static String color="white";//靜態只執行一次
​
    public Car() {
        this.price=9;
        this.color="red";
    }
​
    public Car(double price) {
        this.price = price;
    }
​
    @Override
    public String toString() {
        return  price +"\t"+color;
    }
}

 

package chapter14;
//靜態屬性所有物件共享
public class Homework02 {
    public static void main(String[] args) {
        int num=Frock.getNextNum();
        System.out.println(num);//100100
        int num2=Frock.getNextNum();
        System.out.println(num2);//100200
        Frock []p=new Frock[3];
        p[0]=new Frock();
        p[1]=new Frock();
        p[2]=new Frock();
        for (int i = 0; i < p.length ; i++) {
            System.out.println(p[i].getSerialNumber());//100300-100500
        }
    }
}
class Frock{
    private static int currentNum=100000;
​
    public static int getNextNum() {
        currentNum+=100;
        return currentNum;
    }
    private int serialNumber;
​
    public int getSerialNumber() {
        return serialNumber;
    }
​
    public Frock() {
        serialNumber=getNextNum();
    }
}

 

package chapter14;
​
public class Homework03 {
    public static void main(String[] args) {
        Animal cat = new Cat();
        cat.shout();
        Animal dog = new Dog();
        dog.shout();
​
    }
​
}
abstract class Animal{
    abstract void shout();
}
class Cat extends Animal{
​
    @Override
    void shout() {
        System.out.println("貓叫");
    }
}
class Dog extends Animal{
    @Override
    void shout() {
        System.out.println("狗叫");
    }
}

 

package chapter14;
​
public class Homework04 {
    public static void main(String[] args) {
        new Cellphone().testWork(1,2);
        Cellphone2 C = new Cellphone2();
        C.testWork(new cal(){
​
            @Override
            public double work(double n1, double n2) {//動態繫結
                return n1+n2;
            }
        },2,3);
        C.testWork(new cal() {
            @Override
            public double work(double n1, double n2) {
                return n1*n2;
            }
        },3,6);
    }
}
interface calc{
    void work(double n1,double n2);
}
class Cellphone{
    void testWork(double n1,double n2){
      calc c=  new calc() {
            @Override
            public void work(double n1, double n2) {
                System.out.println(n1+n2);
            }
        };
      c.work(n1,n2);
​
    }
}
interface cal{
    double work(double n1,double n2);
}
class Cellphone2{
   public void testWork(cal d,double n1,double n2){
       double result=d.work(n1,n2);//動態繫結,執行型別是匿名內部類
       System.out.println(result);
   }
}

 

package chapter14;
​
public class Homework05 {
    public static void main(String[] args) {
       new A().f1();
    }
}
class A{
    private static String name="xx";
    public void f1(){
        class B{//區域性內部類,是在方法裡的
            private  final String name="yy";
            void show(){
                System.out.println(name);//就近原則
                System.out.println(A.name);
            }
        }
        B b = new B();//區域性內部類呼叫
        b.show();
    }
​
}

 

package chapter14;
​
public class Homework06 {
    public static void main(String[] args) {
        Person p = new Person("唐僧", new Horse());
        p.common();
        p.passRiver();
        p.passFireHill();//擴充套件
    }
}
interface Vehicles{
    void work();
}
class Horse implements Vehicles{
    @Override
    public void work() {
        System.out.print("用馬");
    }
}
class Boat implements Vehicles{
    @Override
    public void work() {
        System.out.print("用船");
    }
}
class Plane implements Vehicles{
    @Override
    public void work() {
        System.out.print("用飛機");
    }
}
class fac{//獲得工具類(返回建立的物件)
    //優化 餓漢式,保持同一批馬
    private static Horse horse=new Horse();
    public static Horse getHorse(){
        return horse;
    }
    private fac(){}//私有化構造器,防止外部類建立物件
    public static Boat getBoat(){//做成static方法比較方便
        return new Boat();
    }
    public static Plane getPlane(){
        return new Plane();
    }
}
class Person{
    private String name;
    private Vehicles V;
​
    public Person(String name, Vehicles vehicles) {
        this.name = name;
        V = vehicles;
    }
​
    public void passRiver(){//情況動作當方法
        if (!(V instanceof Boat)){//不是船或者空的時候
            V =fac.getBoat();//V的編譯型別Vehicles,向上轉型,執行型別Boat
            V.work();
            System.out.println("過河");
        }
    }
    public void common(){
        if (V==null){
            V =fac.getHorse();
        }
        V.work();
        System.out.println("趕路");
    }
    public void passFireHill(){
        if (!(V instanceof Plane)){
            V =fac.getPlane();
            V.work();
            System.out.println("過火焰山");
        }
    }
}

 

package chapter14;
​
public class Homework07 {
    public static void main(String[] args) {
        Cars cars = new Cars(44.5);
        cars.getAir().flow();
    }
}
class Cars{
    private double temperature;
​
    public Cars(double temperature) {
        this.temperature = temperature;
    }
​
    class Air{
        public void flow(){
            if (temperature>40){
                System.out.println("吹冷氣");
            }else if (temperature<0){
                System.out.println("吹暖氣");
            }else {
                System.out.println("關閉");
            }
        }
    }
    public Air getAir(){//內部類建立
        return new Air();
    }
}

 

package chapter14;
​
public class Homework08 {
    public static void main(String[] args) {
        Color c=Color.BLACK;
        c.show();
        switch (c){
            case RED:
                System.out.println("紅");
                c.show();
                break;
            case BLUE:
                System.out.println("藍");
                c.show();
                break;
            case BLACK:
                System.out.println("黑");
                c.show();
                break;
            case GREEN:
                System.out.println("綠");
                c.show();
                break;
            case YELLOW:
                System.out.println("黃");
                c.show();
                break;
        }
    }
}
interface y{
    void show();
}
enum Color implements y{
    RED(255,0,0),BLUE(0,0,255),BLACK(0,0,0),YELLOW(255,255,0),GREEN(0,255,0);
    private int redValue;
    private int greenValue;
    private int blueValue;
​
    Color(int redValue, int greenValue, int blueValue) {
        this.redValue = redValue;
        this.greenValue = greenValue;
        this.blueValue = blueValue;
    }
​
    @Override
    public void show() {
        System.out.println(redValue+","+greenValue+","+blueValue);
    }
}

 

異常體系

 

 

 

 

五大執行異常

package chapter15.五大執行異常;
//異常處理,加強程式健壯性 ArithmeticException
public class Arithmetic {
    public static void main(String[] args) {
        int num1=10;
        int num2=0;
        try {//若沒有try catch 預設throw給jvm報錯
            int res=num1/num2;//選中以後 Ctrl+alt+t 用try catch包起來
        } catch (Exception e) {//系統將異常封裝成Exception物件e,傳遞給catch
            e.printStackTrace();
            System.out.println("異常原因:"+e.getMessage());//輸出異常資訊
        }
        System.out.println("程式繼續執行");
    }
}

 

package chapter15.五大執行異常;
​
public class ArrayIndexOutOfBounds {
    public static void main(String[] args) {
        int []arr={1,2,4};
        for (int i = 0; i < arr.length+1 ; i++) {
            System.out.println(arr[i]);
        }
    }
}

 

package chapter15.五大執行異常;
​
public class ClassCast {
    public static void main(String[] args) {
       A b = new B();
       B b2=(B)b;//向下轉型,強轉
       C c2=(C)b;//B與C無任何關係
    }
}
class A{}
class B extends A{}
class C extends A{}

 

package chapter15.五大執行異常;
​
public class NullPointer {
    public static void main(String[] args) {
        String name=null;
        System.out.println(name.length());
    }
}

 

package chapter15.五大執行異常;
​
public class NumberFormat {
    public static void main(String[] args) {
        String name="123";
        String h="哈哈";
        int num=Integer.parseInt(name);//String轉成int
        System.out.println(name);
        Integer.parseInt(h);
    }
}

 

 

異常處理

package chapter15.異常處理;
​
public class TryCatch01 {
    public static void main(String[] args) {
        try {
            String h="哈哈";
            Integer.parseInt(h);//String轉成int
            System.out.println("xxx");//異常後不執行
        } catch (NumberFormatException e) {//可用多個異常分別捕獲,子類異常在前父類在後
            System.out.println(e.getMessage());
        } finally {//必執行,含有return優先替代返回
            System.out.println("finally執行....");
        }
        System.out.println("程式繼續....");
    }
}

 

package chapter15.異常處理;
​
public class TryCatch02 {
    public static int method(){
        int i=1;
        try {
            i++;//2
            String[]names=new String[3];
            if (names[1].equals("tom")){//空指標異常,後面不執行
                System.out.println(names[1]);
            }else {
                names[3]="xxxx";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            return 2;
        }catch (NullPointerException b){
            return ++i;//3 儲存,最後返回
        }finally {
            ++i;//4
            System.out.println("i="+i);//優先輸出i=4
        }
​
    }
​
    public static void main(String[] args) {
        System.out.println(method());
    }
}

 

package chapter15.異常處理;
​
import java.util.Scanner;
​
public class TryCatchExercise {
    public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            do {
                    System.out.println("請輸入整數");
                    // int i=scanner.nextInt(); 在try裡 記憶體資料沒有被取出,會誤以為使用者輸入 陷入無限迴圈
                   String input=scanner.next();
                try {
                    int i=Integer.parseInt(input);
                    System.out.println("i="+i);
                    break;
                } catch (NumberFormatException e) {
                    System.out.println("輸入不是整數");
                }
            }while (true);
​
    }
}

 

package chapter15.異常處理;
//throws 異常處理方式,在方法宣告處後跟異常型別
//可丟擲父類異常,多個異常,子類方法只能丟擲父類的子類或相同異常
//丟擲的編譯異常在呼叫者裡必須處理(try catch或繼續丟擲去) 執行異常在呼叫者裡不是必須處理
public class Custom {
    public static void main(String[] args) {
        int age=180;
        if (!(age>=18&&age<=120)){
            throw new AgeException("年齡需18-20之間");//手動生成異常物件關鍵字,在方法體中後跟異常物件,可通過構造器設定資訊
        }
        System.out.println("年齡正確");
    }
}
//自定義異常,一般情況下繼承RuntimeException,即做成執行時異常,可使用預設處理機制(呼叫者不用再丟擲)
class AgeException extends RuntimeException{
    public AgeException(String message) {//構造器
        super(message);
    }
}

 

package chapter15.異常處理;
​
public class ThrowExercise {
    public static void main(String[] args) {
        try {
            ReturnExceptionDemo.methodA();
        }catch (Exception e){
            System.out.println(e.getMessage());//3
        }
        ReturnExceptionDemo.methodB();
    }
}
class ReturnExceptionDemo{
    static void methodA(){
        try {
            System.out.println("進入方法A");//1
            throw new RuntimeException("製造異常");
        }finally {
            System.out.println("用A方法的finally");//2
        }
    }
    static void methodB(){
        try {
            System.out.println("進入方法B");//4
            return;
        }finally {
            System.out.println("呼叫B方法finally");//5
        }
    }
}

 

異常習題

package chapter15.章節作業;
​
public class Homework01 {
    public static void main(String[] args) {
        try {
            if(args.length!=2){
                throw new ArrayIndexOutOfBoundsException("引數個數不對");
            }
            int n1=Integer.parseInt(args[0]);
            int n2=Integer.parseInt(args[1]);
            double res=cal(n1,n2);
            System.out.println(res);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }catch (NumberFormatException e){
            System.out.println("引數格式不正確");
        }catch (ArithmeticException g){
            System.out.println("分母不能為0");
        }
​
    }
    public static double cal(int n1,int n2){
        return n1/n2;
    }
}

 

package chapter15.章節作業;
​
public class Homework02 {
    public static void func() {
        try {
            throw new RuntimeException();
        }finally {
            System.out.println("B");//1
        }
    }
    public static void main(String[] args){
        try {
            func();
            System.out.println("A");//有異常不執行
        }catch (Exception b){
            System.out.println("C");//2
        }
        System.out.println("D");//3 異常處理完了,就執行
    }
}

 

package chapter15.章節作業;
​
public class Homework03 {
    public static void main(String[] args) {
        try{
            showExce();
            System.out.println("A");//不執行
        }catch (Exception e){
            System.out.println("B");//1
        }finally {
            System.out.println("C");//2
        }
        System.out.println("D");//3
    }
    public static void showExce()throws Exception{
        throw new Exception();
    }
}