Java学习第三十七天<面向对象习题><异常体系><五大运行异常><异常处理><异常习题>

2022/4/5 22:49:49

本文主要是介绍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();
    }
}



这篇关于Java学习第三十七天<面向对象习题><异常体系><五大运行异常><异常处理><异常习题>的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程