I have to to a calculator that adds, subtract, multiply and divide the numbers one by one to a stack, and at the end it will show the result of all operations. Example.
Input:10 Input:+ Input:10 Input:= Output: 10+10=20
I tried to do it by manually pushing the numbers and operators, and it worked fine, for adding and subtracting only. (here is the code).
public static void main(String[] args) {
Stack<String> stack = new Stack();
stack.push("10");
stack.push("+");
stack.push("10");
stack.push("-");
stack.push("20");
stack.push("+");
stack.push("1");
stack.push("=");
int result=0;
int i;
int result=0;
for(i=0;i<stack.size();i++){
if (stack.elementAt(i)== "+"){
//does get in
I checked in the second code that the stack is similar to the one on the first code, and it is similar. For some reason, it doesn't want to go through the if statement, even though it is equal to "+" or "-".
Stack<String> stack = new Stack();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String s1 = sc.next();
stack.push(s1);
if(s1.equals("=")) {
break;
}
}
int i;
int result=0;
for(i=0;i<stack.size();i++){
System.out.print(stack.elementAt(i));
}
for(i=0;i<stack.size();i++){
if (stack.elementAt(i)=="+"){
//doesn't get in