第10次作业
题目1:
编写一个应用程序,模拟中介和购房者完成房屋购买过程。
程序代码
(1)Business—— 业务接口
package org.ccut.pack_2; public interface Business { public static final double RATIO=0.022; public static final double TAX=0.03; void buying (double price); }
(2)Buyer —— 购房者类
package org.ccut.pack_2; public class Buyer implements Business{ String name; public Buyer(String name) { this.name = name; } @Override public void buying(double price) { System.out.println(this.name+"购买了一套总价为"+price+"元的住宅。"); } }
(3)Intermediary—— 中介类
package org.ccut.pack_2; public class Intermediary implements Business { Buyer buyer; public Intermediary(Buyer buyer) { this.buyer = buyer; } @Override public void buying(double price) { buyer.buying(price); charing(price); } public void charing(double price){ System.out.println("中介公司收取的中介费用为:"+(price*Business.RATIO)+"元。"); System.out.println("需要交的契税为:"+(price*Business.TAX)+"元。"); } }
(4)Test —— 主类
package org.ccut.pack_2; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); Business business=new Intermediary(new Buyer("Lisa")); System.out.println("请输入要购买的房屋标价:"); double price=scanner.nextDouble(); business.buying(price); } }
运行结果:
题目2:
输入5个数,代表学生成绩,计算其平均成绩。当输入值为负数或大于100时,通过自定义异常处理进行提示。
程序代码
(1)定义一个异常类NumberErrorException 用于处理输入值为负数或大于100时的错误
package org.ccut.pack_3; public class NumberErrorException extends Exception { @Override public String toString() { return "输入值不能为负数或大于100"; } @Override public String getMessage() { return super.getMessage(); } }
(2)主类Test
package org.ccut.pack_3; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); double sum=0.0; double score=0.0; try { for (int i = 0; i < 5; i++) { score=scanner.nextDouble(); if(score<0||score>100) throw new NumberErrorException(); sum+=score; } System.out.println("平均成绩为:"+sum/5); } catch (NumberErrorException e){ System.out.println(e.toString()); } catch (Exception e){ System.out.println(e.getMessage()); } } }
运行结果
(1)正常输入时,
(2)输入负数时,
(3)输入大于100的数时,