I recently started learning java in uni and a task we had to do is to understand recursion and add factorial function to this Polish notation code. I have tried various methods, and this is the latest one:
public class PolishNotation {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Please enter the operators");
System.out.println("for operators +, -, *, and !");
System.out.println("Leave spaces between all operators and digits");
System.out.print("expression: ");
System.out.println("value = " + evaluateEXP(scanner));
}
}
//input contains the expression user has entered
public static int evaluateEXP(Scanner scanner) {
//checks if there is another digit after current one
//allows expression to be looked at from right to left
if (scanner.hasNextInt())
return scanner.nextInt();
//if there is another digit after current one then
//operands and operators are established
char operator = scanner.next().charAt(0);
int operand1 = evaluateEXP(scanner);
int operand2 = evaluateEXP(scanner);
return evaluateOP(operator, operand1, operand2);
}
//operator has to be one of +, - , * or ! otherwise error is given
private static int evaluateOP(char operator, int operand1, int operand2) {
if (operator == '+')
return operand1 + operand2;
if (operator == '-')
return operand1 - operand2;
if (operator == '*')
return operand1 * operand2;
if (operator == '/')
return operand1 / operand2;
if (operator == '!')
//if ! used then uses factorial method
return factorial(operand1);
//RunTimeException allows to return an error string in a int "type" method
throw new RuntimeException("operator not allowed for this language");
}
private static int factorial(int n) {
return n == 1 ? 1 : factorial(n - 1) * n;
}
}
There are no errors, but a result does not come out so I am guessing that it's stuck on an infinite loop. The idea of this code is that if I did ! + 3 2 it should do !5 so return 120 and I cannot use while or for loops. The rest of the operands work, it's just the factorial that doesn't.