【问题标题】:Java doing arithmetic using variable operators [duplicate]Java使用变量运算符进行算术[重复]
【发布时间】:2014-05-05 04:49:59
【问题描述】:

好的,所以变量current 是一个运算符(+-*/%)

t1 = stack.pop() 是字符串形式的数字 t2 = stack.pop() 也是字符串形式的数字

我需要进行数学运算t2 current t1(基本上是t2“运算符”t1)

你会怎么做。提前致谢!

【问题讨论】:

  • 你有没有尝试过?将字符串转换为ints 或floats 之类的,确定它使用的是哪个运算符String.equals 并执行操作。
  • + 是运算符,"+" 是字符串。当您想要连接字符串 t2t1 时,t2 current t1 错误和 t2 + t1 是正确的。要在字符串中添加数字,您必须首先将字符串转换为数字并添加。
  • 将数字字符串转换为数字Double.parseDouble(String)并执行一系列if语句来查找运算符if(Strings.equal("*",operator))等的值
  • 谢谢大家,我已经按照下面提供的答案完成了,我只是想知道是否还有其他方法。

标签: java


【解决方案1】:

简单的:

enum operation {
    SUM,
    SUB,
    DIV,
    MUL,
}

static String performOperation(operation op, String t1, String t2) {
   // parse t1 & t2 into integers or whatever you use
   switch(op) {
   case SUM:
       //do sum
       break;
   case SUB:
       //do substraction
       break;

   // handle all of them....

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 2023-03-29
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多