为什么我的比较子句总是抛出IllegalArgumentException?

时间:2019-05-30 03:48:58

标签: java methods comparison

我正在尝试创建一个计算器方法,我想在我的case语句中使用数学符号,但是我的错误检查总是抛出错误。

我尝试将我的ELSE语句移到最下面,以防排序因某种原因而出现。当我将变量添加到错误消息的末尾时,它似乎可以正确分配它。

公共静态无效值计算器(双firstNumber,字符运算,双secondNumber){

    if (operation != '+' || operation != '-' || operation != '*' || operation != '/' || operation !='%'){
        throw new IllegalArgumentException("You must choose a number between 1 and 5 inclusive." + operation);
    }else{
        if(operation == '/' && secondNumber == 0){
            throw new IllegalArgumentException("Dividend cannot be zero.");
        }else{if(operation == '%' && secondNumber == 0){
                throw new IllegalArgumentException("Dividend cannot be zero.");
            }else

                switch (operation){
                    case '+': System.out.println("1");
                    break;

                    case '-': System.out.println("2");
                    break;

                    case '*': System.out.println("3");
                    break;

....

使用+,%和/的错误示例:

> java.lang.IllegalArgumentException: You must choose a number between 1
> and 5 inclusive.+     at MathUtilites.calculator(MathUtilites.java:39)
> java.lang.IllegalArgumentException: You must choose a number between 1
> and 5 inclusive.%     at MathUtilites.calculator(MathUtilites.java:39)
> java.lang.IllegalArgumentException: You must choose a number between 1
> and 5 inclusive./     at MathUtilites.calculator(MathUtilites.java:39)

我希望它只返回1到5之间的数字,稍后我将用实际代码替换它。

2 个答案:

答案 0 :(得分:0)

就像对您的问题的第一条评论一样,您需要将||替换为&&,这将表明所有这些都必须为真,而不是说 any其中必须是真的。修改您的代码,使其看起来像这样,它应该可以工作:

if (operation != '+' && operation != '-' && operation != '*' && operation != '/' && operation !='%'){
    throw new IllegalArgumentException("You must choose a number between 1 and 5 inclusive." + operation);

答案 1 :(得分:0)

if (operation != '+' || operation != '-' || operation != '*' || operation != '/' || operation !='%'){
    throw new IllegalArgumentException("You must choose a number between 1 and 5 inclusive." + operation);

应该是

if (operation != '+' && operation != '-' && operation != '*' && operation != '/' && operation !='%'){
        throw new IllegalArgumentException("You must choose a number between 1 and 5 inclusive." + operation);
    }

您应该查找与ORAND运算符有关的布尔代数。