Make a program so I can enter a math formula of the same format but with differe
ID: 3530318 • Letter: M
Question
Make a program so I can enter a math formula of the same format but with different numbers. You do not have to use letters, only numbers and ( ) + * - /. You should put all the symbols into a stack or stacks and use the push and pop commands to work the stack. This is predominantly about using stacks. I will enter something like the following: (5+4)*12/4-2. Set your program to display the answer to the expression. I'm stuck on this program. I have one that lets you enter it in postfix, and it works, but I can't get it to work if you enter an expression like (5+4)*12/4-2. If anyone can help me out that would be amazing.Explanation / Answer
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
public class Postfix {
public static void main(String[] args) {
String str;
String output = "";
char popItem = ' ';
Stack<Character> stackList = new Stack<Character>();
System.out.println("enter your string :");
Scanner input = new Scanner(System.in);
str = input.nextLine();
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case '(':
stackList.push(str.charAt(i));
break;
case ')':
popItem = stackList.pop();
while (popItem != '(') {
if (popItem != '(')
output = output + popItem;
popItem = stackList.pop();
}
break;
case '/':
stackList.push(str.charAt(i));
break;
case '*':
stackList.push(str.charAt(i));
break;
case '+':
stackList.push(str.charAt(i));
break;
case '-':
stackList.push(str.charAt(i));
break;
default:
output = output + str.charAt(i);
break;
}
}
Iterator<Character> ilist = stackList.iterator();
while (ilist.hasNext()) {
popItem = stackList.pop();
output = output + popItem;
}
System.out.println("Output is:" + output);
}
}
Output:
enter your string :
(5+4)*12/4-2
Output is:54+1242-/*
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.