刷题的狂欢-----JAVA每日三练-----第八天

第一题 银行账号中现有余额1023.79元。模拟取款,当在控制台上输入的取款金额不是整数时,会引起数字格式转换异常,实现效果如图所示。

import java.util.InputMismatchException;
import java.util.Scanner;

public class Account {
          
    
	public static void main(String[] args) {
          
   
		double leftMoney = 1023.79; // 初始化“账户余额”
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入取款金额:");
		try {
          
    // try块
			int drawMoney = sc.nextInt();
			double result = leftMoney - drawMoney; // 建立变量间的关系
			if(result >= 0) {
          
    // 当余额大于取款金额时
				System.out.println("您账号上的余额:" + (float)result + "元");
			} else {
          
    // 当取款金额超出余额时
				System.out.println("您账号上的余额不足!");
			}
		}
		catch (InputMismatchException e) {
          
    // catch块
			System.out.println("发生数字格式转换异常:输入的“取款金额”不是整数!");
		} finally {
          
   
			sc.close(); // 关闭控制台输入
		}
	}
}

第二题 有位车主想打开车门,不巧的是,他发现自己没带车钥匙,由此引发了空指针异常(NullPointerException),这种场景该如何设计?实现效果如图所示。

public class StartEngine {
          
   
    static void start() throws NullPointerException {
          
   
        Object key = null;
    }

    public static void main(String[] args) {
          
   
        try {
          
   
            start();
        } catch (Exception e) {
          
   
            System.out.println("车钥匙忘带了!车暂时是启动不了了……");
        } finally {
          
   
            System.out.println("去取车钥匙吧T_T");
        }
    }
}

第三题 编写自定义异常CountIsNotIntegerException,当统计的学校的人数为不是整数时,则抛出该异常,实现效果如图所示。

public class CountIsNotIntegerException extends Exception {
          
   

    public CountIsNotIntegerException(String message) {
          
   
        super(message);// 实现父类构造法方法
    }

    public static void main(String[] args) {
          
   
        Number count = 456214.2; 
        School school = new School();
        school.setCount(count);
    }

}

class School {
          
   
    private Number count;

    public void setCount(Number count) {
          
   
        Integer i = count.intValue();// 把人数转为整数
        Double d = count.doubleValue();// 把人数转为浮点数
        double di = i;// 整数付给浮点数
        if (d.equals(di)) {
          
   // 如果两个浮点数数值相同
            this.count = count;
        } else {
          
   // 否则抛异常
            try {
          
   
                throw new CountIsNotIntegerException("人数不能为小数:" + d);
            } catch (CountIsNotIntegerException e) {
          
   
                e.printStackTrace();
            }
        }

    }
}

笔者才疏学浅,请各位师傅不吝赐教。

经验分享 程序员 微信小程序 职场和发展