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

4

我正在尝试在Java中制作一个简单的文本计算器,这是我几乎第一次编写的程序。我无法弄清楚如何将输入的字符串转换为变量opOne。然后,我将尝试使用opOne作为运算符来操作numOnenumTwo

以下是代码:

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

       } 
   }
}

基于文本的计算器。请改用ScriptEngine。例如:1)在网页中(小程序) 2)非 GUI 3)简单 GUI 4)漂亮的 GUI - Andrew Thompson
3个回答

6

最简单的做法是使用一系列的 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("-", 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;
        }
    });
}

如果您初始化了这样一张地图,您可以按照以下方式进行计算:

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

2

你无法将Java字符串转换为运算符。它不是Java数据类型。

   double Calculate(String opOne, double numOne, double numTwo) {  
      if (opOne.equals("+"))  
        return numOne + numTwo;  
      else if (opOne.equals("-"))  
        return numOne - numTwo;  
      else if (opOne.equals("*"))  
        return numOne * numTwo; 
      else if (opOne.equals("/"))  
        return numOne / numTwo;   
    } 

1
计算机本身不知道“运算符”是什么(用人类语言表示),因此您需要告诉计算机如何做到这一点。
String opOne;

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

switch (opOne) {  //Note: String in switch is possible only from Java 7, check your version
     "+": System.out.println('Result: ' + (numOne + numTwo)); break; 
     "-": System.out.println('Result: ' + (numOne - numTwo)); break;
     // and so on...
}

我不能给你点赞,因为我是新手,但我想说一声非常感谢你。 - Cory Liseo
我没有看到任何运行时教学。 - Steve Kuo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接