I am creating this mini program that gives basic math problems to the user, and the user has to answer the questions. I am doing this by creating an array with basic math problems, contains about 20, and the way the user inputs the answer is through a Scanner.
My problems is I have searched and found a way to convert a string with only 1 operator and 2 operands into an int, but I have been trying to modify it so the program can convert the strings that have multiple parts into an int, but I cant. This is what I have
Problems from array:
private String arithProb[] = {
"40 + 20",
"60 - 30 + 60",
"2 * 7 + 40 - 20 + 20 -40"
};
These are just 3 of the 20. The first one outputs the correct answer, which is 60 but the others output the result from the first 2 operands and first operator. second problem only outputs 30. third problem only outputs 14.
Here is the code I am using to convert the string into an int. What am I doing incorrectly or what am I not doing to not get the full thing working?
public static void solveBasicArithmetic(String prob, int ans){
int cAns = evaluateQuestion(prob);
System.out.println();
if(ans == cAns){
System.out.println("CORRECT!");
}else if(ans != cAns){
System.out.println("Oops, the correct answer is: " + cAns);
}
System.out.println();
}
public static int evaluateQuestion(String problem){
Scanner sc = new Scanner(problem);
int finalAns;
do{
//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 "+":
finalAns =+ firstValue + secondValue;
return finalAns;
case "-":
finalAns =+ firstValue - secondValue;
return finalAns;
case "/":
finalAns =+ firstValue / secondValue;
return finalAns;
case "*":
finalAns =+ firstValue * secondValue;
return finalAns;
case "%":
finalAns =+ firstValue % secondValue;
return finalAns;
default: throw new RuntimeException("Unknown operator: " + operator);
}
}while(sc.findInLine("[0-9]*") != null);
}