如何在Java中将字符串转换为运算符?
发布时间:2020-12-15 04:07:56 所属栏目:Java 来源:网络整理
导读:参见英文答案 Is it possible to pass arithmetic operators to a method in java?????????????????????????????????????8个 我试图在java中创建一个简单的基于文本的计算器,我的第一个程序,EVER,我无法弄清楚如何将输入字符串转换为变量opOne.然后,我将尝试
参见英文答案 >
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("-",int b) { return a-b; } }); opByName.put("*",int b) { return a*b; } }); opByName.put("/",int b) { return a/b; } }); } 使用这样初始化的地图,您可以执行如下计算: int res = opByName.get(opOne).calculate(numOne,numTwo); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java – Android Marshmallow 6.0.1打破了我的连续语音识别
- 【SpringCloud】03.微服务的设计原则
- java – Android LoaderManager和CursorLoader混淆
- 如何使用Java 8流迭代嵌套for循环引用父元素?
- java – Autoboxing无法将int转换为Integer
- Mybatis generator 逆向生成代码
- XSLT转换为xmlSignature java?
- java – 如何查找字符串中的所有第一个索引?
- 春天 – 如何编写mockito junit为Resttemplate交换方法
- java – 启动Wildfly(JBoss)服务器时出现VM错误