PTAJava实验六

7-1 jmu-Java-06异常-01-常见异常

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

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"

异常处理学的不好,第一道题思路不清晰,参见:https://blog.csdn.net/weixin_48419914/article/details/121228852

import java.util.Scanner;
 
public class Main {
	public static void main(String[] args) {
		int []nums = new int[5];
		Scanner in = new Scanner(System.in);
		String str = in.next();
		while(str.equals("other")==false) {
			try {
				if(str.equals("null")) {
					throw new NullPointerException();
				}
				else if(str.equals("arr")) {
					int index = in.nextInt();
					if(index>4||index<0) {
						throw new ArrayIndexOutOfBoundsException(""+index);
					}
				}
				else if(str.equals("cast")) {
					throw new ClassCastException("java.lang.String cannot be cast to java.lang.Integer");
				}
				else if(str.equals("num")) {
					String num = in.next();
					if(!(num.charAt(0)>='0'&&num.charAt(0)<='9')) {
						throw new NumberFormatException("For input string: \""+num+"\"");
					}
				}
			}catch (Exception e) {
				System.out.println(e);
			}
			str = in.next();
		}
	}
}

7-2 jmu-Java-06异常-02-使用异常机制处理异常输入

使用异常处理输入机制,让程序变得更健壮。

main方法:
输入n,创建大小为n的int数组。
输入n个整数,放入数组。输入时,有可能输入的是非整型字符串,这时候需要输出异常信息,然后重新输入。
使用Arrays.toString输出数组中的内容。
输入样例:

5
1
2
a
b
4
5
3

输出样例:

java.lang.NumberFormatException: For input string: "a"
java.lang.NumberFormatException: For input string: "b"
[1, 2, 4, 5, 3]
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            try {
                String num = sc.next();
                arr[i] = Integer.parseInt(num);
            } catch (Exception e) {
                System.out.println(e);
                i--;
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}

7-3 jmu-Java-06异常-04-自定义异常(综合)

定义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则新建学生对象。然后输入一行学生数据,格式为姓名 年龄,接着调用setName,addScore。否则跳出循环。
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
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.next();
            if (str.equals("new") == false) {
                sc.close();
                System.out.println("scanner closed");
                break;
            }
            Student stu = new Student();
            sc.nextLine();
            String[] msg = sc.nextLine().split(" ");
            try {
                String name = msg[0];
                int score = Integer.parseInt(msg[1]);
                stu.setName(name);
                stu.addScore(score);
                System.out.println(stu);
            } catch (IllegalScoreException e) {
                System.out.println(e);
            } catch (IllegalNameException e) {
                System.out.println(e);
            } catch (Exception e) {
                System.out.println("java.util.NoSuchElementException");
            }
        }
    }
}

class IllegalScoreException extends Exception {
    String msg;

    public IllegalScoreException(String msg) {
        this.msg = msg;
    }

    public String toString() {
        return "IllegalScoreException: score out of range, score=" + msg;
    }
}

class IllegalNameException extends RuntimeException {
    String msg;

    public IllegalNameException(String msg) {
        this.msg = msg;
    }

    public String toString() {
        return "IllegalNameException: the first char of name must not be digit, name=" + msg;
    }
}

class Student {
    private String name;
    private int score;

    @Override
    public String toString() {
        return "Student [" +
                "name=" + name +
                ", score=" + score +
                ']';
    }

    public int addScore(int score) throws IllegalScoreException {
        if (this.score + score < 0 || this.score + score > 100)
            throw new IllegalScoreException(Integer.toString(this.score + score));
        setScore(this.score + score);
        return 0;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.charAt(0) >= '0' && name.charAt(0) <= '9')
            throw new IllegalNameException(name);
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

7-4 天不假年

程序填空题。根据题目要求完善下面的代码。请提交完整代码。
“今年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
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){
            System.out.println(e.getMessage());
        }
    }
}
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("B");
        }
    }
}
class AgeException extends Exception{
    public AgeException(String msg){
        super(msg);
    }
}

7-5 成绩录入时的及格与不及格人数统计

编写一个程序进行一个班某门课程成绩的录入,能够控制录入成绩总人数,对录入成绩统计其及格人数和不及格人数。设计一个异常类,当输入的成绩小0分或大于100分时,抛出该异常类对象,程序将捕捉这个异常对象,并调用执行该异常类对象的toString()方法,该方法获取当前无效分数值,并返回一个此分数无效的字符串。

输入格式:
从键盘中输入学生人数n

从键盘中输入第1个学生的成绩

从键盘中输入第2个学生的成绩

从键盘中输入第n个学生的成绩

(注:当输入的成绩无效时(即分数为小于0或大于100)可重新输入,且输出端会输出此分数无效的提醒。)

输出格式:
显示及格总人数

显示不及格总人数

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

3
100
30
60

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

2
1

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

2
200
69
30

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

200invalid!
1
1
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int yes = 0;
        int no = 0;
        for (int i = 0; i < n; i++) {
            int score = sc.nextInt();
            try {
                if (score < 0 || score > 100) {
                    throw new IllegalScoreException(Integer.toString(score));
                } else {
                    if (score >= 60) {
                        yes++;
                    } else {
                        no++;
                    }
                }
            } catch (IllegalScoreException e) {
                System.out.println(e);
                i--;
            }
        }
        System.out.println(yes + "\n" + no);
    }
}

class IllegalScoreException extends Exception {
    String msg;

    public IllegalScoreException(String msg) {
        this.msg = msg;
    }

    public String toString() {
        return msg + "invalid!";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Re:从零开始的代码生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值