6-1 异常:物品安全检查 (20分)
这是函数题模板。这里写题目要求。 车站检查危险品的设备,如果发现危险品会发出警告。编程模拟设备发现危险品的情况。编程要求如下:
通过继承Exception类,编写一个DangerException类。 a) 该异常类有构造方法,该构造方法使用super调用父类构造方法,使用字符串:“属于危险品!”,对父类变量message进行初始化。
编写商品类:Goods,该类包含以下成员: a) 私有的name属性(String类型),表示商品名称。 b) 私有的isDanger属性(boolean型),表示商品是否为危险品,如果为危险品,则值为true,否则为fales。 c) 分别为两个私有变量编写set和get方法
编写一个Machine类,该类的方法checkBag(Goods goods)。当发现参数goods是危险品时,即:goods的isDanger属性为true时,该方法抛出DangerException异常的对象。
编写主类Check,在其main方法中创建创建商品对象,并使用Machine对象检查商品。
函数接口定义:
裁判测试程序样例:
public class Main {
public static void main(String args[]) {
String[] name ={"苹果","炸药","西服","硫酸","手表","硫磺"};
Goods[] goods = new Goods[name.length];
for(int i= 0;i<name.length;i++) {
goods[i] = new Goods();
if(i%2==0) {
goods[i].setDanger(false);
goods[i].setName(name[i]);
}
else {
goods[i].setDanger(true);
goods[i].setName(name[i]);
}
}
Machine machine = new Machine();
for(int i= 0;i<goods.length;i++) {
System.out.print(goods[i].getName());
try {
machine.checkBag(goods[i]);
System.out.println(",检查通过\n");
}catch(DangerException e) {
System.out.println(e.getMessage());
System.out.println(goods[i].getName()+",被禁止!\n");
}
}
}
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
输出样例:
在这里给出相应的输出。例如:
苹果,检查通过
炸药属于危险品!
炸药,被禁止!
西服,检查通过
硫酸属于危险品!
硫酸,被禁止!
手表,检查通过
硫磺属于危险品!
硫磺,被禁止!
class DangerException extends Exception{
public DangerException(){
super("属于危险品!");
}
}
class Goods {
private String name;
private boolean isDanger;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDanger() {
return isDanger;
}
public void setDanger(boolean isDanger) {
this.isDanger = isDanger;
}
}
class Machine{
public void checkBag(Goods goods) throws DangerException {
if(goods.isDanger()) {
DangerException danger=new DangerException();
throw danger;
}
// else {
// System.out.println(goods.getName()+"不是危险品");
// }
}
}
7-1 设计一个能处理异常的Loan类 (20分)
定义一个贷款类Loan,其中有属性:
annualInterestRate:double,表示贷款的年利率(默认值:2.5)
numberOfYears:int,表示贷款的年数(默认值:1)
loanAmount:double,表示贷款额(默认值:100)
loanDate:java.util.Date,表示创建贷款的日期
定义方法:
(1)默认的无参构造方法
(2)带指定利率、年数和贷款额的构造方法
(3)所有属性的get/set方法
(4)返回这笔贷款的月支付额getMonthlyPayment()
月支付额 = (贷款额度月利率)/(1-(1/Math.pow(1+月利率,年数12)))
(5)返回这笔贷款的总支付额getTotalPayment()
总支付额度 = 月支付额度年数12
附上如下的测试类。
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
double AIR = input.nextDouble();
int NOY = input.nextInt();
double LA = input.nextDouble();
try {
Loan m = new Loan(AIR, NOY, LA);
System.out.printf("%.3f\n",m.getTotalPayment());
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
输入格式:
输入有多组数据,一个实数表示年利率,一个整数表示年数,一个实数表示贷款总额。
输出格式:
若任意一项小于或等于零,抛出IllegalArgumentException异常及相应描述(Number of years must be positive或Annual interest rate must be positive或Loan amount must be positive);有多项不符合,以不符合最前项为准;
若均符合要求,按照格式输出总额。
输入样例:
在这里给出一组输入。例如:
1 1 1000
2.0 0 2000
0 0 0
输出样例:
在这里给出相应的输出。例如:
1005.425
java.lang.IllegalArgumentException: Number of years must be positive
java.lang.IllegalArgumentException: Annual interest rate must be positive
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
double AIR = input.nextDouble();
int NOY = input.nextInt();
double LA = input.nextDouble();
try {
Loan m = new Loan(AIR, NOY, LA);
System.out.printf("%.3f\n",m.getTotalPayment());
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
class Loan{
private double annualInterestRate;
private int numberOfYear;
private double loanAmount;
private Date loanDate;
public Loan() {
this.annualInterestRate =2.5;
this.numberOfYear = 1;
this.loanAmount = 100;
}
public Loan(double annualInterestRate, int numberOfYear, double loanAmount) {
if(annualInterestRate<=0) {
throw new IllegalArgumentException("Annual interest rate must be positive");
}
else this.annualInterestRate = annualInterestRate;
if(numberOfYear<=0)
throw new IllegalArgumentException("Number of years must be positive");
else this.numberOfYear = numberOfYear;
if(loanAmount<=0) {
throw new IllegalArgumentException("Loan amount must be positive");
}
else this.loanAmount = loanAmount;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public int getNumberOfYear() {
return numberOfYear;
}
public void setNumberOfYear(int numberOfYear) {
this.numberOfYear = numberOfYear;
}
public double getLoanAmount() {
return loanAmount;
}
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
public Date getLoanDate() {
return loanDate;
}
public void setLoanDate(Date loanDate) {
this.loanDate = loanDate;
}
public double getMonthlyPayment() {
double monthlyrate=this.getAnnualInterestRate()/1200;
double MonthlyPayment=(this.getLoanAmount()*monthlyrate)/(1-(1/Math.pow(1+monthlyrate,this.getNumberOfYear()*12 )));
return MonthlyPayment;
}
public double getTotalPayment() {
return this.getMonthlyPayment()*this.getNumberOfYear()*12;
}
}
在构造函数中设置抛出异常
7-2 设计一个Tiangle异常类 (20分)
创建一个IllegalTriangleException类,处理三角形的三边,任意两边之和小于等于第三边,则显示三条边不符合要求。
然后设计一个有三条边的Triangle的类。如果三条边不符合要求,则抛出一个IllegalTriangleException异常。
三角形的构造方法如下:
public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {
//实现
}
一个名为toString()的方法返回这个三角形的字符串描述。
toString()方法的实现如下所示:
return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" + side3 + "]";
编写一个测试程序如下,用户输入三角形的三条边,然后显示相应信息。 提交时,将此测试程序附在后面一起提交。 测试程序:
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s1 = input.nextDouble();
double s2 = input.nextDouble();
double s3 = input.nextDouble();
try {
Triangle t = new Triangle(s1,s2,s3);
System.out.println(t);
}
catch (IllegalTriangleException ex) {
System.out.println(ex.getMessage());
}
}
}
输入格式:
输入三条边
输出格式:
如果三条边正确,则输出toString()的信息,否则,输出IllegalTriangleException: 非法的边长
例如,输入1 1 1,则输出Triangle [side1=1.0, side2=1.0, side3=1.0]
若输入 1 2 3,则输出Invalid: 1.0,2.0,3.0
输入样例:
在这里给出一组输入。例如:
1 2 3
输出样例:
在这里给出相应的输出。例如:
Invalid: 1.0,2.0,3.0
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double s1 = input.nextDouble();
double s2 = input.nextDouble();
double s3 = input.nextDouble();
try {
Triangle t = new Triangle(s1,s2,s3);
System.out.println(t);
}
catch (IllegalTriangleException ex) {
System.out.println(ex.getMessage());
}
}
}
//创建一个IllegalTriangleException类,处理三角形的三边,任意两边之和小于等于第三边,则显示三条边不符合要求
class IllegalTriangleException extends Exception{
public IllegalTriangleException(String message) {
super(message);
}
}
//然后设计一个有三条边的Triangle的类。如果三条边不符合要求,则抛出一个IllegalTriangleException异常。
class Triangle{
double side1;
double side2;
double side3;
public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {
this.side1=side1;
this.side2=side2;
this.side3=side3;
if(this.side1+this.side2<=this.side3||this.side2+this.side3<=this.side1||this.side1+this.side3<=this.side2)
{
throw new IllegalTriangleException("Invalid: "+this.side1+","+this.side2+","+this.side3);
}
}
public String toString() {
return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" + side3 + "]";
}
}
7-3 较为复杂情况下的求和-hebust (10分)
计算一个给定序列的整数和,序列中可能会混入无关的字母,求和的时候需要忽略。
输入格式:
输入为一行,元素直接使用空格分割。
输出格式:
输出为序列整数部分的和。
输入样例:
在这里给出一组输入。例如:
1 2 3 a 4 5
输出样例:
在这里给出相应的输出。例如:
15
利用异常处理机制跳过异常情况
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] ns = s.split(" ");
for (int i = 0; i < ns.length; i++) {
try {
sum += Integer.parseInt(ns[i]);
}catch (Exception e){
continue;//发现异常,直接跳过
}
}
System.out.println(sum);
}
}
7-4 InputMismatchException异常 (20分)
(InputMismatchException异常)编写一个程序,提示用户读取两个整数,然后显示它们的和。程序应该在输入不正确时提示用户再次读取数值。
输入格式:
输入多组两个数
输出格式:
输出两个数的和
输入样例:
在这里给出一组输入。例如:
1 3
2.0 3
3.0 4
4 5
输出样例:
在这里给出相应的输出。例如:
sum = 4
Incorrect input: two integer is required
Incorrect input: two integer is required
sum = 9
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
boolean flag=true;
while (cin.hasNext()||flag) {
try {
//System.out.println("请输入两个整数:");
int a = cin.nextInt();
int b = cin.nextInt();
int sum =a + b;
System.out.println("sum = " +sum);// 输入的数字不是整数时不会往下执行,跳转到catch语句块中执行
flag = false;// 当输入的两个数都是整数的时候,才会执行到这条语句
} catch (InputMismatchException e) {
System.out.println("Incorrect input: two integer is required");
cin.nextLine();// 清空输入的数字
}
}
}
}