Shorter solution to if,else if,else if

前端 未结 6 1813
深忆病人
深忆病人 2021-01-06 08:58

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 &quo

6条回答
  •  有刺的猬
    2021-01-06 09:44

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

提交回复
热议问题