如何在Java中将字符串转换为运算符?
我试图用java编写一个简单的基于文本的计算器,这是我的第一个程序,但我不知道如何将输入如何在Java中将字符串转换为运算符?,java,string,calculator,Java,String,Calculator,我试图用java编写一个简单的基于文本的计算器,这是我的第一个程序,但我不知道如何将输入字符串转换为变量opOne。然后,我将尝试使用opOne作为操作员,针对numTwo操作numOne。 代码如下: import java.io.*; import java.math.*; public class ReadString { public static void main (String[] args) { System.out.print("Enter the f
字符串
转换为变量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");
}
}
}
int res = opByName.get(opOne).calculate(numOne, numTwo);
计算机本身不知道操作员是什么(人类语言),所以你需要告诉计算机去做
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...
}
最简单的方法是一系列
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;
}
});
}
无法将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)2)3)4)。。