Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter solution to if,else if,else 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);
}

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

like image 685
Clay Banks Avatar asked Dec 01 '22 03:12

Clay Banks


1 Answers

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);
like image 100
FDinoff Avatar answered Dec 04 '22 13:12

FDinoff