SDUT PTA异常习题练习
7-8 设计一个能处理异常的Loan类 (20 分)
import java.util.*;
class Loan{
double annualInterestRate=25;
double numberOfYears=1;
double loanAmount=100;
Date loanDate=new Date();
public Loan() {
}
public Loan(double annualInterestRate, double numberOfYears, double loanAmount) throws IllegalArgumentException {
super();
if (annualInterestRate<=0)
try {
throw new IllegalArgumentException("Annual interest rate must be positive");
}
catch(IllegalArgumentException e) {
throw new IllegalArgumentException("Annual interest rate must be positive");
}
else if (numberOfYears<=0)
try {
throw new IllegalArgumentException("Number of years must be positive");
}
catch(IllegalArgumentException e) {
throw new IllegalArgumentException("Number of years must be positive");
}
else if (loanAmount<=0)
try{
throw new IllegalArgumentException("Loan amount must be positive");
}
catch(Exception e) {
throw new IllegalArgumentException("Loan amount must be positive");
}
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getNumberOfYears() {
return numberOfYears;
}
public void setNumberOfYears(double numberOfYears) {
this.numberOfYears = numberOfYears;
}
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 mo=annualInterestRate/1200;//注意年利率=月利率/1200;
return loanAmount*mo/(1-(1/Math.pow(1+mo, numberOfYears*12)));
}
public double getTotalPayment() {
return getMonthlyPayment()*12*numberOfYears;
}
}
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);
}
}
input.close();
}
}
7-9 设计一个Tiangle异常类 (20 分)
第一个自己写的代码
import java.util.*;
class Triangle{
double a;
double b;
double c;
int flag=0;
public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {
if(side1+side2<=side3
||side1+side3<=side2
||side2+side3<=side1)
{
try {//如果不符合条件,则抛出异常
throw new IllegalTriangleException(side1,side2,side3);
}
catch(IllegalTriangleException e) {//上面抛出了,这里一定获取
throw new IllegalTriangleException(side1,side2,side3);//因为主函数没有抛出,所以这里抛出
}
}
else {
a=side1;
b=side2;
c=side3;
}
}
@Override
public String toString() {
return "Triangle [side1=" + a + ", side2=" + b + ", side3=" + c + "]";
}
}
class IllegalTriangleException extends Exception{
public IllegalTriangleException() {
super();
}
public IllegalTriangleException(double a,double b,double c) {
super("Invalid: " + a +","+ b+ ","+ c );
}
}
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double s1 = sc.nextDouble();
double s2 = sc.nextDouble();
double s3 = sc.nextDouble();
try {
Triangle t = new Triangle(s1,s2,s3);
System.out.println(t);
}
catch (IllegalTriangleException ex) {
System.out.println(ex.getMessage());
}
sc.close();
}
}
7-5 成绩录入时的及格与不及格人数统计 (10 分)
这个代码思想比较深
import java.util.*;
class MyException extends Exception //自定义异常类
{
MyException (){
}
MyException(int s)
//自定抛出的方法:int s代表传入的数据
{
super(s+"invalid!");//向屏幕打印的数据
}
}
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n =in.nextInt();
int cont1=0,cont2=0;
ArrayList<Integer> c = new ArrayList <> (n);
//创建动态数组,因为数组容量会增加(题目要求输入非法值时,需要重新输入一个新值)
for(int j=0;j<n;j++)
{
int z= in.nextInt();
c.add(z);//将输入的值放进动态数组内。
if(z>100||z<0)
n++;
}
for(int a:c) //遍历数组里的每一个值。
{
try{
if(a>100||a<0)
throw new MyException(a);
if(a<=100&&a>=60)
cont1++;
if(a>=0&&a<60)
cont2++;
}
catch(MyException e)
{
System.out.println(e.getMessage());
//会去除MyException这些字符
}
}
System.out.println(cont1);
System.out.println(cont2);
}
}
7-3 jmu-Java-06异常-04-自定义异常(综合) (15 分)
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s;
while (true){
s= sc.nextLine();
if (s.equals("new")){
Student stu=new Student();
String s1=sc.nextLine();
String[] ss=s1.split(" ");
try {
stu.setName(ss[0]);
}catch (Exception e){
continue;
}
try{
stu.addScore(Integer.parseInt(ss[1]));
}catch (Exception e){
stu.flag=false;
System.out.println("java.util.NoSuchElementException");
}
if (stu.flag) System.out.println(stu);
}else if (s.equals("other")){
break;
}
}
sc.close();
System.out.println("scanner closed");
}
}
class IllegalScoreException extends RuntimeException{
public IllegalScoreException() {
}
public IllegalScoreException(String message) {
super(message);
}
}
class IllegalNameException extends RuntimeException{
public IllegalNameException() {
}
public IllegalNameException(String message) {
super(message);
}
}
class Student{
private String name;
private int score;
boolean flag=true;
public String getName() {
return name;
}
public void setName(String name) {
if (name.charAt(0)>='0'&&name.charAt(0)<='9'){
try{
throw new IllegalNameException("the first char of name must not be digit, name=");
//如果首字母为数字,则直接抛出IllegalNameException
}catch (IllegalNameException e){
flag=false;
System.out.println(e+name);
}
}else {
this.name = name;
}
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [" +
"name=" + name +
", score=" + score +
']';
}
public int addScore(int score){
this.score=this.score+score;
if (this.score>100||this.score<0){
try{
throw new IllegalScoreException("score out of range, score=");
//如果加分后分数<0 或>100,则直接抛出IllegalScoreException,加分不成功
}catch (IllegalScoreException e){
flag=false;
System.out.println(e.toString()+score);
}
}
return this.score;
}
}
7-4 天不假年 (5 分)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
age = sc.nextInt();
Person p = new Person(age);
age = sc.nextInt();
try {
p.setAge(age);
} catch (AgeException e) {
System.out.println("B");
return;
}
System.out.println("A");
sc.close();
}
}
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 {
//异常的建立好像是套路题,直接套用就行
public AgeException() {
super();
}
public AgeException(String message) {
super(message);
}
}
7-7 InputMismatchException异常 (20 分)
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int ans=0;
while(sc.hasNext()) {
String t=sc.next();
try {
double ddd=Double.parseDouble(t);
int cnt=(int) Math.round(ddd);
ans+=cnt;
}
catch(Exception e){
continue;
}
}
System.out.println(ans);
sc.close();
}
}
7-7 InputMismatchException异常 (20 分)
//如果直接获取int,会无限循环,原因未知
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String a=sc.next();
String b=sc.next();
int ans=0;
int flag=1;
try {
int cnt=Integer.parseInt(a);
ans+=cnt;
cnt=Integer.parseInt(b);
ans+=cnt;
}
catch(Exception e){
flag=0;
System.out.println("Incorrect input: two integer is required");
continue;
}
if(flag==1)
System.out.println("sum = "+ans);
}
sc.close();
}
}