Hi I need this coded in Java. This is a warm up project for me to understand the
ID: 3851063 • Letter: H
Question
Hi I need this coded in Java. This is a warm up project for me to understand the project I will be diving in. The code should be fairly simple but I just do not understand it.
Edit* ignore the polish notation comment in the photo I want the output to be like I had noted below. I will further explain below to clarify myself
I need this coded in java where you can input any expression as a string like (((1+2)÷3)×4) and it follows the logic of the node tree below on the picture of the white board it shows how it should be set up. I want the code to include a text scanner to of course input the line then print out the solution without the parenthesis except on the 1st calculation of the expression. The example of the output is so. The 2 outputs it would print back out are (1+2)÷3×4 and the result that follows the logic 4.
Thank You
Explanation / Answer
FileName:EvaluateString.java
import java.util.Scanner;
import java.util.Stack;
public class EvaluateString
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
// Stack for numbers: 'values'
Stack<Integer> values = new Stack<Integer>();
// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();
for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.toString()));
}
// Current token is an opening brace, push it to 'ops'
else if (tokens[i] == '(')
ops.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')')
{
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.empty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Top of 'values' contains result, return it
return values.pop();
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
// Driver method to test above methods
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String inputExpression;
String requiredInput="";
System.out.println("Enter the expression to be evaluated with proper paranthesis");
inputExpression=sc.nextLine();
for(int i=0;i<inputExpression.length();i++)
{
requiredInput+=inputExpression.charAt(i);
requiredInput+=" ";
}
StringBuffer sb =new StringBuffer(inputExpression);
sb.delete(0, 1);
sb.delete(sb.length()-1, sb.length());
System.out.print("Given Input is "+sb+" and the output is:");
System.out.println(EvaluateString.evaluate(requiredInput));
}
}