【问题标题】:how to use the a string value for arithmetic equations?如何将字符串值用于算术方程?
【发布时间】:2018-01-01 06:06:19
【问题描述】:

我正在尝试编写一个计算算术表达式值的方法。该方法采用两个 int 参数 value1 和 value2 以及一个字符串参数运算符。如果运算符不是 *、/、- 或 + 或者 / 后面的 value2 为 0,我会抛出 IllegalArgumentException。

如何让字符串值在算术表达式中起作用?到目前为止,这是我拥有的代码:

  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);
  }

【问题讨论】:

  • if(operator.equals("+")) result = value1+value; else if(....,否则使用String and parse the whole expresseion
  • 谢谢,我的程序可以运行了。

标签: java string methods throw arithmetic-expressions


【解决方案1】:

我认为对你来说最好的选择是 switch case,请看这个示例代码:

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;

在这种情况下,默认情况将替换第一个 If 检查,您将能够将其删除。

【讨论】:

  • 别忘了检查case "/":是否有除0
  • 我发现这很有帮助,它比以前更好地组织了我的程序。
  • @JURO312 请注意,您需要 java 7+ 才能在开关中使用 String。
猜你喜欢
  • 2023-03-09
  • 2018-07-06
  • 2017-01-10
  • 2019-03-24
  • 2021-11-13
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
相关资源
最近更新 更多