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

标签 java string calculator

<分区>

我正在尝试用 java 制作一个简单的基于文本的计算器 我的第一个程序,EVER 但我不知道如何将输入 String 转换为变量 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;
} ...

一种高级方法是为您的运算符(operator)定义一个接口(interface),并将实例放入 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;
        }
    });
}

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

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

关于java - 如何在 Java 中将字符串转换为运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15169507/

相关文章:

c++ - 在 C++ 中使用 std::istringsteam 将字符串转换为 float

string - bash 中的子字符串替换

regex - 无法通过子例程通过正则表达式替换字符串

android - 在编辑文本中多次按零,但用户应该只能看到一位数字,如计算器

java - 计算器编码错误。请更正

Java比较这个类和那个类是否相等

java - 如何在 JEE 中定义处理多部分数据的 JAX-RS 服务?

java - 使用父类(super class)实例构造子类

java - Spark数据集获取与整数列标题相同的数据

jquery - try catch 表单提交事件,然后不再捕获它