第10次作业

题目1:

编写一个应用程序,模拟中介和购房者完成房屋购买过程。

代码:

业务接口

 1 package 中介和购房者;
 2 
 3 /**
 4  * 接口类: Business,包括两个成员变量一个方法
 5  *
 6  */
 7 public interface Business {
 8     double RATIO = 0.022;
 9     double TAX = 0.03;
10 
11     void buying(double price);
12 }

购房者类

 1 package 中介和购房者;
 2 
 3 /**
 4  * Buyer继承Business接口,包含一个成员变量和一个重写的方法。
 5  *
 6  */
 7 public class Buyer implements Business {
 8     String name;
 9 
10     public Buyer(String name) {
11         this.name = name;
12     }
13 
14     public void buying(double price) {
15 
16         System.out.println(name + "购买一套标价为" + price + "的房子");
17     }
18 }

中介类

 1 package 中介和购房者;
 2 
 3 /**
 4  * 中介类Intermediary继承Business接口 包含一个成员变量,一个构造方法,一个重写方法,一个实例方法
 5  *
 6  */
 7 public class Intermediary implements Business {
 8 
 9     Buyer buyer;
10 
11     public Intermediary(Buyer buyer) {
12         this.buyer = buyer;
13 
14     }
15 
16     public void buying(double price) {
17         buyer.buying(price);
18         this.charing(price);
19     }
20 
21     public void charing(double price) {
22         System.out.println("中介费为:" + price * RATIO);
23         System.out.println("契税:" + price * TAX);
24 
25     }
26 
27 }

测试类

 1 package 中介和购房者;
 2 
 3 /**
 4  * 测试类:实现中介买房的过程
 5  *
 6  */
 7 public class Test {
 8     public static void main(String[] args) {
 9         Buyer buyer = new Buyer("Lisa");
10         Intermediary intermediary = new Intermediary(buyer);
11         intermediary.buying(650000);
12     }
13 }

运行截图:

题目2:

输入5个数,代表学生成绩,计算其平均成绩。当输入值为负数或大于100时,通过自定义异常处理进行提示。

代码:

自定义异常类

 1 package 平均成绩异常处理;
 2 
 3 /**
 4  * 自定义异常类,继承自异常类,重写了toString方法,包含一个构造方法和一个实例变量
 5  *
 6  */
 7 public class MyException extends Exception {
 8 
 9     double num;
10 
11     public MyException(double num) {
12         this.num = num;
13     }
14 
15     public String toString() {
16 
17         return "输入越界异常:" + num + "不在0~100范围内,程序被迫退出";
18     }
19 
20 }

测试类

 1 package 平均成绩异常处理;
 2 /**
 3  * 测试类
 4  */
 5 import java.util.Scanner;
 6 
 7 public class Test {
 8     public static void main(String[] args) {
 9         double arr[] = new double[5];
10         int sum = 0, avg = 0;
11         Scanner scanner = new Scanner(System.in);
12         System.out.println("请输入5名学生的成绩");
13         try {
14             for (int i = 0; i < arr.length; i++) {
15                 arr[i] = scanner.nextDouble();
16                 if (arr[i] > 100 || arr[i] < 0)
17                     throw new MyException(arr[i]);
18                 sum += arr[i];
19             }
20             System.out.println("平均分为:" + sum / arr.length);
21         } catch (MyException e) {
22             System.out.println(e.toString());
23         }
24 
25     }
26 }

测试截图:

posted @ 2019-11-13 16:10  刘明康20194682  阅读(136)  评论(0编辑  收藏  举报