ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-04-05 22:02:28  阅读:116  来源: 互联网

标签:void System class 第三十七 println 习题 异常 public out


面向对象习题

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();
    }
}

标签:void,System,class,第三十七,println,习题,异常,public,out
来源: https://www.cnblogs.com/wybqjcdd/p/16104144.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有