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
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With