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

Cor*_*seo 3 java string calculator

我试图在java中创建一个简单的基于文本的计算器我的第一个程序,EVER,我无法弄清楚如何将输入String转换为变量opOne.然后我会尝试numOne反对numTwo使用opOne作为运营商.代码如下:

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

       } 
   }
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

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

if ("+".equals(opOne)) {
    res = numOne + numTwo;
} else if ("-".equals(opOne)) {
    res = numOne - numTwo;
} ...
Run Code Online (Sandbox Code Playgroud)

一种高级方法是为运算符定义接口,并将实例放在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("-", new Operation() {
        public int calculate(int a, int b) {
            return a-b;
        }
    });
    opByName.put("*", new Operation() {
        public int calculate(int a, int b) {
            return a*b;
        }
    });
    opByName.put("/", new Operation() {
        public int calculate(int a, int b) {
            return a/b;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

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

int res = opByName.get(opOne).calculate(numOne, numTwo);
Run Code Online (Sandbox Code Playgroud)