Skip to content

Instantly share code, notes, and snippets.

@RupGautam
Last active March 24, 2017 21:47
Show Gist options
  • Select an option

  • Save RupGautam/61c76c07a1c75cd349b5de70056e69e0 to your computer and use it in GitHub Desktop.

Select an option

Save RupGautam/61c76c07a1c75cd349b5de70056e69e0 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class evaluateExpression {
// http://www.careercup.com/question?id=4911380140392448
public static void main(String[] args) {
// An equation with +, -, /, *
String anotherEquation;
System.out.print("Please enter math Expression: ");
Scanner kb = new Scanner(System.in);
anotherEquation = kb.nextLine();
int another = computeAnother(anotherEquation);
System.out.println(another);
}
static int computeAnother(String equation) {
int result = 0;
String noMinus = equation.replace("-", "+-");
String[] byPluses = noMinus.split("\\+");
for (String multipl : byPluses) {
String[] byMultipl = multipl.split("\\*");
int multiplResult = 1; //
for (String operand : byMultipl) {
if (operand.contains("/")) {
String[] division = operand.split("\\/");
int divident = Integer.parseInt(division[0]);
for (int i = 1; i < division.length; i++) {
divident /= Integer.parseInt(division[i]);
}
multiplResult *= divident;
} else {
multiplResult *= Integer.parseInt(operand);
}
}
result += multiplResult;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment