加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在Java中将字符串转换为运算符?

发布时间:2020-12-15 04:07:56 所属栏目:Java 来源:网络整理
导读:参见英文答案 Is it possible to pass arithmetic operators to a method in java?????????????????????????????????????8个 我试图在java中创建一个简单的基于文本的计算器,我的第一个程序,EVER,我无法弄清楚如何将输入字符串转换为变量opOne.然后,我将尝试
参见英文答案 > Is it possible to pass arithmetic operators to a method in java?????????????????????????????????????8个
我试图在java中创建一个简单的基于文本的计算器,我的第一个程序,EVER,我无法弄清楚如何将输入字符串转换为变量opOne.然后,我将尝试使用opOne作为运算符对numTwo运行numOne.
代码如下:

import java.io.*;
import java.math.*;

public class ReadString {

   public static void main (String[] args) {


      System.out.print("Enter the first number: ");


      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      int numOne = 0 ;
      int numTwo = 0 ;
      String opOne = null;

      while(true){
      try {
          numOne = Integer.valueOf(br.readLine());
          break;
      } catch (IOException error) {
         System.out.println("error; try again.");
         System.exit(1);
      }
      catch (NumberFormatException nfe) {
          System.out.println("error;try again.");

      }

      }

      System.out.print("Enter the second number: ");

      while(true){
      try {

          numTwo = Integer.valueOf(br.readLine());
          break;
       } catch (IOException error2) {
          System.out.println("error");
          System.exit(1);
       } catch (NumberFormatException nfe) {
          System.out.println("error;try again.");

       }
      }

      System.out.println("What would you like to do with " + numOne + " and " + numTwo + "?");

      try {
          operator = br.readLine();
       } catch (IOException ioe) {
          System.out.println("error");
          System.exit(1);
       } catch (NumberFormatException nfe) {
          System.out.println("error");

       } 
   }
}

解决方法

这样做的最简单方法是if-then-else语句序列:

if ("+".equals(opOne)) {
    res = numOne + numTwo;
} else if ("-".equals(opOne)) {
    res = numOne - numTwo;
} ...

一种高级方法是为运算符定义接口,并将实例放在Map容器??中:

interface Operation {
    int calculate(int a,int b);
}

static final Map<String,Operation> opByName = new HashMap<String,Operation>();
static {
    opByName.put("+",new Operation() {
        public int calculate(int a,int b) {
            return a+b;
        }
    });
    opByName.put("-",int b) {
            return a-b;
        }
    });
    opByName.put("*",int b) {
            return a*b;
        }
    });
    opByName.put("/",int b) {
            return a/b;
        }
    });
}

使用这样初始化的地图,您可以执行如下计算:

int res = opByName.get(opOne).calculate(numOne,numTwo);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读