2021-06-18 Java程序设计基础--实验7

7-1 测试抛出异常 (20 分)

尝试构造类ArrayUtil,该类的方法int findMax(int[] arr, int begin, int end)能抛出IllegalArgumentException(表示参数错误)的方法。 正常执行要求begin<=end

如果begin>=end,抛出异常(IllegalArgumentException),异常信息为 “begin:x >= end:x”

如果begin<0,抛出异常(IllegalArgumentException),异常信息为 “begin:x < 0”

如果end>arr.length,抛出异常(IllegalArgumentException),异常信息为 “end:x > arr.length”

要求在findMax方法声明处声明此异常,在main函数里要捕获此异常,并输出异常类型(可用obj.getClass().getName())和异常信息

输入格式:
输入n,表示int数组大小

输入n个整数,放入数组。

输入m,表示begin和end的对数

输入m对整数,代表begin与end,然后调用ArrayUtils.findMax方法。

输出格式:
异常信息

数组的最大值

输入样例:
在这里给出一组输入。例如:

5
1 2 3 4 5
6
0 5
3 3
3 4
3 2
-1 3
0 6

输出样例:
在这里给出相应的输出。例如:

5
java.lang.IllegalArgumentException: begin:3 >= end:3
4
java.lang.IllegalArgumentException: begin:3 >= end:2
java.lang.IllegalArgumentException: begin:-1 < 0
java.lang.IllegalArgumentException: end:6 > arr.length

Accepted Code

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int n = scan.nextInt();
		int[] arr = new int[n];
	
		for (int i = 0; i < n; i++) {
			arr[i] = scan.nextInt();
		}
		
		int m = scan.nextInt();
		for (int i = 0; i < m; i++) {
			int begin = scan.nextInt();
			int end = scan.nextInt();
			int max = ArrayUtil.findMax(arr, begin, end);
		}
		
		scan.close();
	}
}

class ArrayUtil {
	
	
	public static int findMax(int[] arr, int begin, int end) {
		if (begin >= end) {
			System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" >= end:"+end);
		} else if (begin < 0) {
			System.out.println("java.lang.IllegalArgumentException: begin:"+begin+" < 0");
		} else if (end > arr.length) {
			System.out.println("java.lang.IllegalArgumentException: end:"+end+" > arr.length");
		} else {
		 	int max = Integer.MIN_VALUE;
			for(int i = begin; i < end; i++) {
				if(arr[i] > max) {
					max = arr[i];
				}
			}
			System.out.println(max);
		}
		return 0;
	}
}

7-2 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

Accepted Code

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		boolean judge = true;
		while (scan.hasNext()) {
			try {
				int a = scan.nextInt();
				int b = scan.nextInt();
				int sum = a + b;
				System.out.println("sum = " + sum);
			} catch (InputMismatchException e) {
				System.out.println("Incorrect input: two integer is required");
				scan.nextLine();	//clear input
			}
		}
		
		
		scan.close();
	}
}

7-3 jmu-Java-06异常-01-常见异常 (20 分)

自己编码以产生常见异常。

###main方法:

事先定义好一个大小为5的数组。

根据屏幕输入产生相应异常

提示:可以使用System.out.println(e)打印异常对象的信息,其中e为捕获到的异常对象。

**输入说明: **

arr 代表产生访问数组是产生的异常。然后输入下标,如果抛出ArrayIndexOutOfBoundsException异常则显示,如果不抛出异常则不显示。
null,产生NullPointerException
cast,尝试将String对象强制转化为Integer对象,产生ClassCastException。
num,然后输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。
其他,结束程序。
输入样例:

arr 4
null
cast
num 8
arr 7
num a
other

输出样例:

java.lang.NullPointerException
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
java.lang.ArrayIndexOutOfBoundsException: 7
java.lang.NumberFormatException: For input string: "a"

Accepted Code


import java.util.*;
import java.lang.*;
public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int[] arr = new int[5];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int)Math.random();
		}
		boolean judge = true;
		
		while (scan.hasNext()) {
			String string = scan.next();
			try {
				if (string.equals("arr")) {
					int no = scan.nextInt();
					int a = arr[no];
				} else if (string.equals("null")) {
					throw new NullPointerException();
				} else if (string.equals("cast")) {
					//String s = scan.next();
					throw new ClassCastException("java.lang.String cannot be cast to java.lang.Integer");
				} else if (string.equals("num")) {
					int b = Integer.parseInt(scan.next());
				} else {
					break;
				}
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println(e);
			} catch (NullPointerException e) {
				System.out.println(e);
			} catch (ClassCastException e) {
				System.out.println(e);
			} catch (NumberFormatException e) {
				System.out.println(e);
			}
		}
		
		
		scan.close();
	}
}

7-4 jmu-Java-06异常-04-自定义异常(综合) (20 分)

定义IllegalScoreException异常类,代表分数相加后超出合理范围的异常。该异常是checked exception,即希望该异常一定要被捕获处理。

定义IllegalNameException异常类,代表名字设置不合理的异常。该异常是unchecked exception

定义Student类。

属性:

private String name;
private int score;

方法:

toString          //自动生成
setter/getter     //自动生成
改造setName       //如果姓名首字母为数字则抛出IllegalNameException
public int addScore(int score)  //如果加分后分数<0 或>100,则抛出IllegalScoreException,加分不成功。

###main方法:

输入new则新建学生对象。然后输入一行学生数据,格式为姓名 年龄,接着调用setNameaddScore。否则跳出循环。
setName不成功则抛出异常,并打印异常信息,然后继续下一行的处理。
addScore不成功则抛出异常,并打印异常信息,然后继续下一行的处理。如果2、3都成功,则打印学生信息(toString)
如果在解析学生数据行的时候发生其他异常,则打印异常信息,然后继续下一行的处理。
Scanner也是一种资源,希望程序中不管有没有抛出异常,都要关闭。关闭后,使用System.out.println("scanner closed")打印关闭信息
注意:使用System.out.println(e);打印异常信息,e为所产生的异常。

输入样例:

new
zhang 10
new
wang 101
new
wang30
new
3a 100
new
wang 50
other

输出样例:

Student [name=zhang, score=10]
IllegalScoreException: score out of range, score=101
java.util.NoSuchElementException
IllegalNameException: the first char of name must not be digit, name=3a
Student [name=wang, score=50]
scanner closed

Accepted Code

import java.util.*;
import java.lang.*;
public class Main {

	public static void main(String[] args) throws Exception {
		Scanner scan = new Scanner(System.in);
		
		
		while (scan.hasNextLine()) {
			String string = scan.nextLine();
			try {
				
				if (string.equals("new")) {
					String ns = scan.nextLine();
					String[] s = ns.split(" ");
					if (s.length != 2) {
						throw new NoSuchElementException();
					} else {
						String name = s[0];
						int score = Integer.parseInt(s[1]);
						Student student = new Student();
						student.setName(name);
						student.addScore(score);
						System.out.println(student.toString());
					}
					
				} else {
					break;
				}
				
			} catch (IllegalScoreException e) {
				System.out.println(e);
			} catch (IllegalNameException e) {
				System.out.println(e);
			} catch (NoSuchElementException e) {
				System.out.println(e);
			} catch (Exception e) {
				System.out.println(e);
			}
		}
		try {
			scan.close();
		} finally {
			System.out.println("scanner closed");
			scan.close();
		}
		
	}
}

class Student {
	public String name;
	public int score;
	
	public Student(String str, int s) {
		name = str;
		score = s;
	}
	
	public Student() {
		name = "";
		score = 0;
	}
	
	@Override
	public String toString() {
		String outPut = new String("Student [name=" + name + ", score=" + score + "]");
		return outPut;
	}
	
	public void setName(String name) throws IllegalNameException {
		char ch = name.charAt(0);
		if (ch <= '9' && ch >= '0') {
			throw new IllegalNameException("the first char of name must not be digit, name=" + name);
		} else {
			this.name = name;
		}
	}
	
	public int addScore(int s) throws IllegalScoreException {
		int res = score + s;
		if (res > 100 || res < 0) {
			throw new IllegalScoreException("score out of range, score=" + res);
		} else {
			score = res;
		}
		return score;
		
	}
	
}

class IllegalScoreException extends Exception {
	
	public IllegalScoreException() {}
	
	public IllegalScoreException(String se) {
		super(se);
	}
	
}

class IllegalNameException extends Exception {
	
	public IllegalNameException() {}
	
	public IllegalNameException(String se) {
		super(se);
	}
	
}

7-5 天不假年 (20 分)

程序填空题。根据题目要求完善下面的代码。请提交完整代码。 “今年50,明年18”是一个美好的愿望。人的年龄只能不断增长。 Person类的setAge方法用于更新年龄。 如果新的年龄比原来的年龄小,则输出B表示发现异常,否则输出A表示正常。

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int age;
        age = in.nextInt();
        Person p = new Person(age);        
        age = in.nextInt();
        try{
            p.setAge(age); 
        }catch(AgeException e){             
        }       
    }
}
class Person{
   int age;
   public Person(int age){
       this.age = age;
   }
   public void setAge(int age) throws AgeException {
       if(this.age <=age){
          this.age = age;
       }else{
         throw new AgeException();
       }
   }   
}
class AgeException extends Exception{
}

输入格式:
输入在一行中给出2个绝对值不超过100的正整数A和B。

输出格式:
在一行中输出一个字符A或者B。

输入样例:

50 18

输出样例:

B

Accepted Code

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int age;
        age = in.nextInt();
        Person p = new Person(age);        
        age = in.nextInt();
        try{
            p.setAge(age); 
        }catch(AgeException e){   
        	System.out.println("B");
        }       
    }
}
class Person{
   int age;
   public Person(int age){
       this.age = age;
   }
   public void setAge(int age) throws AgeException {
       if(this.age <=age){
          this.age = age;
          System.out.println("A");
       }else{
         throw new AgeException();
       }
   }   
}
class AgeException extends Exception{
}

7-6 设计一个能处理异常的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

Accepted Code

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 numberOfYears;
	private double loanAmount;
	private Date loanDate;
	
	public Loan() {
		annualInterestRate = 2.5;
		numberOfYears = 1;
		loanAmount = 100;
		loanDate = new Date();
	}

	public Loan(double aIR, int nOY, double lA) {
		if (aIR <= 0) {
			throw new IllegalArgumentException("Annual interest rate must be positive");
		} else if (nOY <= 0) {
			throw new IllegalArgumentException("Number of years must be positive");
		} else if (lA <= 0) {
			throw new IllegalArgumentException("Loan amount must be positive");
		}
		annualInterestRate = aIR;
		numberOfYears = nOY;
		loanAmount = lA;
		loanDate = new Date();
	}
	
	public double getAnnualInterestRate() {
		return annualInterestRate;
	}
	
	public double getLoanAmount() {
		return loanAmount;
	}
	
	public Date getLoanDate() {
		return loanDate;
	}
	
	public int getNumberOfYears() {
		return numberOfYears;
	}
	
	public void setAnnualInterestRate(double annualInterestRate) {
		this.annualInterestRate = annualInterestRate;
	}
	
	public void setLoanAmount(double loanAmount) {
		this.loanAmount = loanAmount;
	}
	
	public void setLoanDate(Date loanDate) {
		this.loanDate = loanDate;
	}
	
	public void setNumberOfYears(int numberOfYears) {
		this.numberOfYears = numberOfYears;
	}
	
	private double getMonthlyPayment() {
		return (this.loanAmount * this.annualInterestRate / 1200) / (1 - (1 / Math.pow(1 + this.annualInterestRate / 1200, this.numberOfYears * 12)));	
	}
	
	public double getTotalPayment() {
		return getMonthlyPayment() * this.numberOfYears * 12;
	}
	
}

7-7 设计一个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

Accepted Code

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());
	      }
	  }
}

class Triangle {
	private double side1;
	private double side2;
	private double side3;
	
	public Triangle(double s1, double s2, double s3) throws IllegalTriangleException {
		
		if(!((s1 + s2) > s3 && (s1 + s3) > s2 && (s2 + s3) > s1)) {
			throw new IllegalTriangleException("Invalid: " + s1 + "," + s2 +"," + s3);
		} else {
			side1 = s1;
			side2 = s2;
			side3 = s3;
		}
	}
	
	@Override
	public String toString() {
		return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" + side3 + "]";
	}
	
}

class IllegalTriangleException extends Exception {
	public IllegalTriangleException() {}
	public IllegalTriangleException(String sq) {
		super(sq);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值