Reputation: 1087
I have to calculate this expression (5+7)*(9-4)+12, using the Stack and RPL (57+94-*12+)
I loop through each element in the given array. When it is a number, I push it to the stack. When it is an operator, I pop two numbers from the stack, do the calculation, and push back the result.
So, here's my code. but there are errors in lines 33, 34, and 53 with valueOf method ( The method valueOf(String) in the type Integer is not applicable for the arguments (Object) )
Can You help me? Thanks!
package mainPackage;
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] massive = {"5", "7", "+", "9", "4", "-", "*", "12", "+"};
int result = calculate(massive);
System.out.println(result);
}
public static int calculate(String[] mas) {
Stack stack = new Stack();
int sum = 0;
String operators = "+-*/";
for (String s : mas) {
if ( !operators.contains(s)) {
stack.push(s);
}
else {
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch (s) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(b - a));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(b / a));
break;
}
}
}
sum = Integer.valueOf(stack.pop());
return sum;
}
}
Upvotes: 0
Views: 214
Reputation: 5937
The stack is storing Objects
rather than Integers. You have to explicitly cast them to Strings. The compiler can't tell that they're Strings without you telling it, so it assumes you're trying to valueOf
an Object
, which is a superclass of String
.
int a = Integer.valueOf((String)stack.pop());
int b = Integer.valueOf((String)stack.pop());
Alternatively, you can mention the type you intend to store in your declaration for the stack.
Stack<String> stack = new Stack<String>(); //Java 6
or
Stack<String> stack = new Stack<>(); //Java 7+
For additional reading on inheritance and casting, you can check out this tutorial.
Upvotes: 2