计算器尝试并捕获Java程序

时间:2012-08-02 01:12:24

标签: java try-catch calculator

我正在尝试制作一个try / catch程序计算器,它可以删除以下错误,但它无效。请告诉我我做错了什么。我应该测试非法操作数操作并将其除以零。

do // do while is for many operations
{
    try
    {
        System.out.println("Enter num1 and num2 : ");
        int num1 = new Scanner();
        int num2 = new Scanner();
        System.out.println("Enter sign : ");
        char sign = new Scanner();
    }
    catch(IllegalArgumentException ex) // This will check for illegal inputs
    {
        System.out.println(ex.Message()); //Will print error message
    }

    if(sign == '+')
    { // part of code where you will write the plus operation
        System.out.println(num1+num2);
    }
    if(sign == '-')
    {
        System.out.println(num1-num2);
    }
    if(sign == '*')
    {
        System.out.println(num1*num2);
    }
    if(sign == '/')
    {
        try
        {
            System.out.println(num1/num2);
        }
        catch(ArithmeticException ex)// Check for divide by zero exception
        {
            System.out.println("Divide by zero");
        }
    }

    if(sign == 'x') // to exit
    {
        flag = false
    }

    else
    {
        System.out.println("Error : Unknown Operator\n");
    }

}while(flag == true) // flag will be true until user enters 'x' as the choice to exit.

2 个答案:

答案 0 :(得分:4)

您将Scanner对象分配给int变量,而不是编译。

您正在寻找的是:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

我建议您阅读扫描仪文档:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

答案 1 :(得分:0)

首先,可能更紧迫,您的代码有一些明显的语法问题。之前提到某些语句甚至无法编译 - int num1 = new Scanner()不合适,因为{{3} }。

其次,也许最重要的是,你的程序有一个严格的线性流程。假设我只想添加两个数字。好吧,我运气不好,因为我每次都要经历并加,减,乘和除数。

在这种情况下,合理地规范您的代码是非常重要的。使用an int is not an object, and an empty constructor isn't one of the choices for a new Scanner来完成此任务。

public Long add(Long value1, Long value2) {
    return value1 + value2;
}

// and so forth

每当你想要进行特定操作时,你可以通过捕获输入来实现这一点 - 从“添加”一词,基于文本的菜单(输入1添加)或其他方式。

至于除零,你不使用try...catch块。通常你会围绕不想破坏的代码执行此操作,因此它在分裂方法,或当你试图划分时。

public Long divide(Long value1, Long value2) throws ArithmeticException {
    return value1 / value2;
}

当您使用该方法时,您需要:

Long a = new Long(300);
Long b = new Long(0);

try {
    divide(a, b);
} except(ArithmeticException, ae) {
    System.out.println("Can't divide by zero");
}

我将整个项目的流程和建设留给您,但这应该会给您一个良好的开端。

相关问题