题目1:
编写一个应用程序,模拟中介和购房者完成房屋购买过程。
共有一个接口和三个类:
- Business—— 业务接口
- Buyer —— 购房者类
- Intermediary—— 中介类
- Test —— 主类
1.业务接口
业务接口包括:
(1)两个数据域(成员变量)
RATIO: double型,代表房屋中介收取的中介费用占房屋标价的比例,初值为0.022
TAX:double型,代表购房需要交纳的契税费用占房屋标价的比例,初值为0.03
(2)一个方法
void buying (double price):price表示房屋总价
package Work1;
public interface Business {
double RATIO = 0.022;
double TAX = 0.03;
void buying(double price);
}
2.购房者类
购房者类Buyer是业务接口Business的非抽象使用类,包括:
(1)一个成员变量
name:String型,表示购房者姓名
(2)一个方法:
public void buying (double price):显示输出购买一套标价为price元的住宅
package Work1;
public class Buyer implements Business {
String name;
Buyer(String name) {
this.name = name;
}
@Override
public void buying(double price) {
// TODO Auto-generated method stub
System.out.println("购买住宅的价格为" + price);
}
}
3.中介类
中介类Intermediary是业务接口Business的非抽象使用类,包括:
- 一个成员变量
buyer:Buyer型,代表房屋中介接待的购房对象
- 三个方法
Intermediary(Buyer buyer):构造方法
public void buying (double price):购房者buyer购买一套标价为price元的住宅,之后计算需要支付的中介费和交纳的契税
public void charing(double price):表示计算购买标价为price元的住宅时,房屋中介需要收取的中介费和需要交纳的契税(中介费计算公式:房屋标价* RATIO,契税计算公式:房屋标价*TAX)
package Work1;
public class Intermediary implements Business {
Buyer buyer;
Intermediary(Buyer buyer) {
this.buyer = buyer;
}
@Override
public void buying(double price) {
// TODO Auto-generated method stub
System.out.println(buyer.name + "购买住宅的价格为" + price + "需要支付的中介费" + Business.RATIO * price + "需要支付的契税为"
+ Business.TAX * price);
}
public void charing(double price) {
System.out.println(
"购买标价为" + price + "元" + "房屋中介需要收取的中介费" + Business.RATIO * price + "需要支付的契税为" + Business.TAX * price);
}
}
4.Test类
在Test类中定义购房对象——姓名Lisa,从控制台输入她计划买的房屋标价,如650000元。请你通过上面定义的接口和类,实现她通过中介买房的过程,显示需交纳的中介费和契税。
package Work1;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
Buyer buyer = new Buyer("Lisa");
double price = reader.nextDouble();
buyer.buying(price);
Intermediary spend = new Intermediary(buyer);
spend.buying(price);
spend.charing(price);
}
}
运行成功截图:
题目2:
输入5个数,代表学生成绩,计算其平均成绩。当输入值为负数或大于100时,通过自定义异常处理进行提示。
package Work1;
import java.util.Scanner;
class MyException extends Exception {
private int exceptnumber;
MyException(int a){
exceptnumber=a;
}
public String toString(){
return "输入值为负数或大于100";
}
}
package Work1;
import java.util.Scanner;
public class T {
public static double makeExcept() throws MyException {
int score;
int sum = 0;
Scanner reader = new Scanner(System.in);
System.out.println("请输入5个成绩:");
for (int i= 0; i<5;i++) {
score = reader.nextInt();
if (score<0||score>100) {
throw new MyException(score); // 抛出自定义异常;
}
sum+=score;
}
return (double) (sum/5);
}
public static void main(String args[]) {
try {
System.out.println("平均成绩是" + makeExcept());
} catch (MyException a) {
System.out.print("程序异常 " + a);
}
}
}
运行成功截图: