JAVA实验六

1、编写应用程序,从命令行输入表示两个小数参数的字符串,求它们的商,要求程序中捕获 NumberFormatException 异常和 ArithmeticException 异常。

import java.util.Scanner;
public class ExtDemo02 {
    public static void main(String[] args) {
        while (true) {
            try {
                System.out.println("输入两个数字:");
                Scanner s = new Scanner(System.in);
                double a = Double.parseDouble(s.nextLine());
                double b = Double.parseDouble(s.nextLine());
                if (b == 0) {
                    throw new ArithmeticException("除零异常,不能除0");
                }
                double c = a / b;
                System.out.println(c);
                break;
            }
                catch(NumberFormatException e){
                    System.out.println("数字格式异常");
                    continue;
                }catch(ArithmeticException e){
                    System.out.println("除数不能为0");
                    continue;
                }
        }
    }
}

 

 

2、编写一段程序,完善学生 student 类,增加输入学生的成绩的操作方法,如果小于 0 分或者大于 100 分则抛出异常,并捕捉异常,输出提示信息:输入的学生成绩超出范围了!

 

import java.util.Scanner;
public class ExtDemo02 {
    public static void main(String[] args){
        while(true) {
            System.out.println("请输入成绩");
            Scanner s = new Scanner(System.in);
            int score = s.nextInt();
            Student student = new Student();
            student.setNo(2020189016);
            student.setName("丁");
            student.setAge(22);
            try {
                student.setScore(score);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(student);
        }
    }
}
class Student{
    private int no;
    private String name;
    private int age;
    private int score;
    public String getScore(){
        if(score>=60)
            return "成绩合格";
        else
            return "成绩不合格";
    }
    public void setScore(int score) throws Exception {
        if(score > 100 || score < 0) throw new Exception("输入的成绩不合理");
        this.score = score;
    }
    public int getNo(){
        return no;
    }
    public void setNo(int no){
        this.no = no;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public int getAge(){
        return age;
    }
    public String toString(){
        return("学号:"+getNo()+",姓名:"+getName()+",年龄:"+getAge()+",成绩情况:"+getScore());
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值