"10-4"
is not a simple integer, it's a calculation, so parsing it to an int
will yield no results..
You'll have to parse your string..
int aa = evaluteQuestion(questionArray[0]);
And the actual magic happens here:
public static int evaluteQuestion(String question) {
Scanner sc = new Scanner(question);
// get the next number from the scanner
int firstValue = Integer.parseInt(sc.findInLine("[0-9]*"));
// get everything which follows and is not a number (might contain white spaces)
String operator = sc.findInLine("[^0-9]*").trim();
int secondValue = Integer.parseInt(sc.findInLine("[0-9]*"));
switch (operator){
case "+":
return firstValue + secondValue;
case "-":
return firstValue - secondValue;
case "/":
return firstValue / secondValue;
case "*":
return firstValue * secondValue;
case "%":
return firstValue % secondValue;
// todo: add additional operators as needed..
default:
throw new RuntimeException("unknown operator: "+operator);
}
}
If you have more parts in your expressions, you might want to put the code above into a loop. watch out for order of operation though. Things might get a little hairy if you want to implement a proper parser for any expression