简体   繁体   English

如何将字符串值用于算术方程式?

[英]how to use the a string value for arithmetic equations?

I'm trying to write a method that computes the value of an arithmetic expression. 我正在尝试编写一种计算算术表达式值的方法。 The method takes two int parameters value1 and value2 and a string parameter operator. 该方法采用两个int参数value1和value2以及一个字符串参数运算符。 I'm suppose to throw an IllegalArgumentException if the operator isn't *, /, -, or + or if / is followed a value2 of 0. 我想如果运算符不是*,/,-或+,或者如果/后面跟着value2为0,则抛出IllegalArgumentException。

How would I get a string value to work in an arithmetic expression? 如何获得字符串值以在算术表达式中工作? So far this is the code I have: 到目前为止,这是我拥有的代码:

  public static int compute(int value1, String operator, int value2)
  {
  if ((!operator.equals("+")) || (!operator.equals("*")) || 
     (!operator.equals("-")) || (!operator.equals("/")))
     {
        throw new IllegalArgumentException("Invalid Operator");
     }
  if ((operator.equals("/")) && (value2 == 0))
     {
        throw new IllegalArgumentException("Divide by 0 error");
     }
     int result; 
     return result = (value1 + operator + value2);
  }

I think best option for you is switch case, see this example code: 我认为最适合您的选择是开关盒,请参见以下示例代码:

int result;

switch (operator)
{
    case "+":
              result = value1 + value2;
              break;
    case "-":
              result = value1 - value2;
              break;
    case "*":
              result = value1 * value2;
              break;
    case "/":
              //check if value2 is 0 to handle divide by zero exception
              if(value2 != 0)
                  result = value1 / value2; 
              else
                  System.out.println("DIVISION NOT POSSIBLE");

              break;
    default:
             throw new IllegalArgumentException("Invalid operator: " + operator);

}

return result;

And in this case the default case will replace the first If check and you will be able to remove it. 在这种情况下,默认情况下将替换第一个If检查,您将能够删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM