参见英文答案 > 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("-", 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);