if的更短解决方案,否则if,否则if [英] Shorter solution to if,else if,else if

查看:155
本文介绍了if的更短解决方案,否则if,否则if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找缩短此代码的方法,避免重复代码和if语句。我正在做的是创建一个计算器,在字符串中搜索运算符* / + - 并相应地执行它们。有什么想法?

I'm looking for a way to shorten this code up and avoid repeating code and if statements. What I'm doing is creating a calculator that searches strings for operators "* / + - " and executes them accordingly. Any ideas?

if(exp.charAt(i)=='*')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) * Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 
        else if(exp.charAt(i)=='/')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) / Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 
        else if(exp.charAt(i)=='+')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) + Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 
        else if(exp.charAt(i)=='-')
        {
            newResult=Integer.parseInt(exp.substring(0, i)) - Integer.parseInt(exp.substring(i+1, exp.length()));
            primeResult = newResult;
            System.out.println(primeResult);
        } 

此外,是否有接受包含2个以上操作数的字符串的解决方案?即5 + 10 * 2/3

Also, is there a solution to accept a string with more than 2 operands? i.e. 5 + 10 * 2 / 3

推荐答案

为了更改代码,您可以使用switch语句并放入一些冗余代码在切换之前或之后。

For changing the code you could use a switch statement and putting some of the redundant code before or after the switch.

int left = Integer.parseInt(exp.substring(0,i));
int right = Integer.parseInt(exp.substring(i+1,exp.length()));
switch(exp.charAt(i)){
    case '*':
        primeResult = left * right;
        break;
    case '/':
        ...
        break;
    case '+':
        ...
        break;
    case '-':
        ...
        break;
    default:
        ... // Error Handling.
}
System.out.println(primeResult);

这篇关于if的更短解决方案,否则if,否则if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆