实验四-单元测试

import java.util.*;
public class jisuan {
    public static void main(String[] args) {
        System.out.println("运算符号位:+,-,*,/");
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入第一个数字:");
        String str=sc.nextLine();
        System.out.println("请输入第二数字:");
        String str2=sc.nextLine();
        System.out.println("请输入运算符:");
        String str3=sc.nextLine();
        try{
        double a=Double.parseDouble(str);
        double b=Double.parseDouble(str2);
        Core core=new Core();
        core.fengzhuan(str3, a, b);
        }catch(NumberFormatException e){
            System.out.println("输入有误,请重新输入");
            Core core= new Core();
            System.out.println("请输入第一个数字:");
            String str4=sc.nextLine();
            System.out.println("请输入第二数字:");
            String str5=sc.nextLine();
            double a=Double.parseDouble(str4);
            double b=Double.parseDouble(str5);
            core.fengzhuan(str3, a, b);
        }
        finally{}
    }
}
class Core {
    Scanner g=new Scanner(System.in);
    public void fengzhuan(String op,double a,double b){
        if(op.equals("+")){
            System.out.println(a+b);
        }else if(op.equals("-")){
            System.out.println(a-b);
        }else if(op.equals("*")){
            System.out.println(a*b);
        }else if(op.equals("/")){
            if(b==0){
                System.out.println("运算错误请重新输入");
                System.out.println("请输入b的值:");
                b=g.nextDouble();
                System.out.println(a/b);
            }
            else if(b!=0){
                System.out.println(a/b);
            }
            }
        else{
            String str3;
            System.out.println("符号输入有误,请重新输入");
            str3=g.next();
             jisuan2 ji=new jisuan2(); 
             ji.huansuan(str3, a, b);
        }
    }
}
class jisuan2 extends jisuan{
    Scanner sc=new Scanner(System.in);
    public void huansuan(String str3,double a,double b){
        if(str3.equals("+")){
            System.out.println(a+b);
        }else if(str3.equals("-")){
            System.out.println(a-b);
        }else if(str3.equals("*")){
            System.out.println(a*b);
        }else if(str3.equals("/")){
            if(b==0){
                System.out.println("运算错误请重新输入");
                System.out.println("请输入b的值:");
                b=sc.nextDouble();
                System.out.println(a/b);
            }
            else if(b!=0){
                System.out.println(a/b);
            }
            }
    }
    

本程序我的想法是首先写出简单的四则运算,然后测试成功。接着就是解决异常的方向想,首先解决数字上的异常,通过异常捕抓然后在让用户输入一遍,使运算正确,最后就是输入符号的异常,我是通过if-else语句来解决的,如果判断符号不是+,-*,/就然用户重新输入一遍。这个程序让我复习了Java异常的捕抓,让我对如何处理异常更加理解了。

posted on 2015-05-06 15:10  57杨家安  阅读(180)  评论(2编辑  收藏  举报