Alternative way to replace Nested While Loop in Java - java

I tried to Evaluate Mathematical Expressions in Java with the following code:
public double applyOp(char op,double b,double a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return 0;
}
public boolean hasPrecedence(char op1,char op2)
{
return (op1 != '*' && op1 != '/') || (op2 != '+' && op2 != '-');
}
public double evaluate(String input) {
Stack<Double> values = new Stack<>();
Stack<Character> ops = new Stack<>();
int stringIndex = 0;
while (stringIndex < input.length())
{
StringBuilder multiDigitsNumber = new StringBuilder();
// If the input is number put to stack values
if (input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
while (stringIndex < input.length() && input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
multiDigitsNumber.append(input.charAt(stringIndex++));
}
values.push(Double.parseDouble(multiDigitsNumber.toString()));
}
// If the input is operator put to stack ops
else
{
while (!ops.empty() && hasPrecedence(input.charAt(stringIndex),ops.peek()))
{
values.push(applyOp(ops.pop(),values.pop(),values.pop()));
}
ops.push(input.charAt(stringIndex++));
}
}
// Execute remain operator in stack values
while (!ops.empty()) {
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
// The final number in stack value is result
return values.pop();
}
Input example:
12+24*2-30/5.....
The code above works fine but I wonder are there any way to replace
while (stringIndex < input.length() && input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
multiDigitsNumber.append(input.charAt(stringIndex++));
}
with something else so I don't have to use nested while loop in this situation. The goal is to catch number in string until it reach an operator
Thanks in advance

You can use Regex like this.
if (input.charAt(stringIndex) >= '0' && input.charAt(stringIndex) <= '9')
{
String number = input.substring(stringIndex).replaceAll("^(\\d+).*", "$1");
values.push(Double.parseDouble(number));
stringIndex += number.length();
}

Related

String Index Exception

I was trying to convert an expression from infix form to postfix form.I used String a, p , s for stack, postfix result expression, input expression respectively.
Every time I am getting this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.charAt(String.java:658) at
javaapplication4.A.conversion(A.java:50) at
javaapplication4.A.main(A.java:83)
Please help me how can I solve it.
Here is my code:
import java.util.Scanner;
public class A {
String a="(", s = "", p = "";
int i, n = 1, top = 0, pp = 0;
void push(char ch) {
a = a + ch;
top = n;
n++;
}
void pop() {
n--;
top--;
}
int prio(char ch) {
int f = -1;
if (ch == '(') {
f = 0;
} else if (ch == '+' || ch == '-') {
f = 1;
} else if (ch == '*' || ch == '/' || ch == '%') {
f = 2;
} else if (ch == '^') {
f = 3;
}
return f;
}
void conversion() {
System.out.print("Enter infix form: ");
Scanner sd = new Scanner(System.in);
s = sd.nextLine();
//System.out.println(s);
int t, j, sz;
sz = s.length();
for (i = 0; i < sz; i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
p = p + s.charAt(i);
pp++;
} else if (s.charAt(i) == '(') {
push('(');
} else if (s.charAt(i) == '-' || s.charAt(i) == '+' || s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%' || s.charAt(i) == '^') {
j = prio(s.charAt(i));
t = prio(a.charAt(top));
//System.out.println(t+" "+j);
while (j <= t) {
p = p + a.charAt(top);
pp++;
pop();
t = prio(a.charAt(top));
}
push(s.charAt(i));
} else if (s.charAt(i) == ')') {
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
}
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
void postfix() {
System.out.print("postfix form is: ");
System.out.println(p);
}
public static void main(String args[]) {
A h = new A();
h.conversion();
h.postfix();
//System.out.println(h.a);
//System.out.println(h.s);
}
}
Can you confirm if the error is here?
while (a.charAt(top) != '(')
Inside the loop you continuously pop(), which decrements from top, which has the risk of going negative if a match is never found. Even if the error is not here, it should check for that condition.
You may have made an extra pop() definition. Can you check this?

program get error Exception in thread "main" java.lang.NumberFormatException: when iterate a math expression [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 2 years ago.
When I try to use the function to iterate the user input expression, I get the java.lang.NumberFormatException, I try fixing the loop much time, but I still cannot understand where did it when wrong. The IDE suggest it went wrong in the parstInt while loop
Here is the code:
import java.util.Scanner;
import java.util.Stack;
static Stack<Integer> stackForOperand = new Stack<Integer>();
static Stack<Character> stackForOperator = new Stack<Character>();
public static int processOneOperator(char stackForOperator, int num1, int num2) {
int result = 0;
switch (stackForOperator) {
case '+':
result = num1 + num2;
case '-':
result = num1 - num2;
case '*':
result = num1 * num2;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
throw new UnsupportedOperationException("divide by zero error");
}
}
return result;
}
public static boolean num_order(char first, char second) {
if (first == '(' || second == ')') {
return false;
} else if ((first == '*' || first == '/') && (second == '+' || second == '-')) {
return false;
} else {
return true;
}
}
public static int calculation_loop(String expression) {
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
String more_num = "";
while (i < expression.length() && expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
more_num += expression.charAt(i++);
int more_num2 = Integer.parseInt(more_num);
stackForOperand.push(more_num2);
i--;
}
} else if (expression.charAt(i) == '(') {
stackForOperator.push(expression.charAt(i));
} else if (expression.charAt(i) == ')') {
while (stackForOperator.peek() != '(') {
stackForOperand.push(
processOneOperator(stackForOperator.pop(), stackForOperand.pop(), stackForOperand.pop()));
stackForOperator.pop();
}
} else if (expression.charAt(i) == '+' || expression.charAt(i) == '-' || expression.charAt(i) == '*'
|| expression.charAt(i) == '/') {
while (!stackForOperator.empty() && num_order(expression.charAt(i), stackForOperator.peek())) {
stackForOperand.push(
processOneOperator(stackForOperator.pop(), stackForOperand.pop(), stackForOperand.pop()));
stackForOperator.push(expression.charAt(i));
}
}
}
while (!stackForOperator.empty()) {
stackForOperand
.push(processOneOperator(stackForOperator.pop(), stackForOperand.pop(), stackForOperand.pop()));
}
return stackForOperand.pop();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("/");
String input = scanner.nextLine();
input = input.replaceAll("\\s+", "");
System.out.println(input);
Integer output = calculation_loop(input);
System.out.println(output);
}
}
Looking at this piece of code:
public static int calculation_loop(String expression) {
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
String more_num = "";
while (i < expression.length() && expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
more_num += expression.charAt(i++);
int more_num2 = Integer.parseInt(more_num);
stackForOperand.push(more_num2);
i--;
}
So. Suppose having such an expression "2345+6789". According to your code i is incrementing and decrementing before end of while loop.
while (i < expression.length() && expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
more_num += expression.charAt(i++);
...
i--;
}
Is this your intention? It makes your loop infinite and it finishes only because number format exception is thrown while parsing. This is why I think your parser throws exception: You got the digit '2' in first place, concatenate it with more_num, then increment the i, after that decrement the i and at the next iteration you have the same previous position with same char '2', then concatenate it again to more_num ad infinitum. And first you parse more_num which is "2", on next iteration you append one more '2' and more_num "22" then "222"... Till it become bigger than type int can hold like "22222222222222222222222" and exception is thrown
Second thing. Suppose you remove i-- and your loop will normally iterate the next char. So, your stackForOperand will push first the number 2, then will push the number 23 then the number 234, then will push the number 2345. Is that your intension? I think more logically is to move Integer.parseInt and stackForOperand.push after the while loop
public static int calculation_loop(String expression) {
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
String more_num = "";
while (i < expression.length() && expression.charAt(i) >= '0' && expression.charAt(i) <= '9') {
more_num += expression.charAt(i++);
}
int more_num2 = Integer.parseInt(more_num);
stackForOperand.push(more_num2);

Why does this method always return false?

I would like to evaluate a phone number using the provided method. The phone number should always have a length of 10. However the following method always seems to return false. Why is that? Thanks.
public static boolean valPhoneNumber(String phonenumber){
boolean result= true;
if (phonenumber.length() > 10 || phonenumber.length() < 10){
result= false;
}else
phonenumber.length();
char a=phonenumber.charAt(0);
char b=phonenumber.charAt(1);
char d=phonenumber.charAt(3);
char e=phonenumber.charAt(4);
char f=phonenumber.charAt(5);
if (a<2 || a>9){
result = false;
}else if( b<0 || b>8){
result = false;
}else if (d<2 || d>9){
result = false;
}else if (e==1 && f==1){
result = false;
}
return result;
}
So looking into your ladder which is comparing character to number. In this case the comparison will happen with ASCII value.
You can put single quotes to check the range:
if (a < '2' || a > '9') {
result = false;
} else if( b < '0' || b > '8') {
result = false;
} else if (d < '2' || d > '9') {
result = false;
} else if (e == '1' && f == '1') {
result = false;
}
One liner:
result = !((a < '2' || a > '9') || (b < '0' || b > '8') || (d < '2' || d > '9') || (e == '1' && f == '1'));
I think your code wrong at the parsing phonenumber.charAt(). This always return char, and when you do comparision with integer it will convert to number which present to that char code (ASCII code). I think you should modify your code to int a=Character.getNumericValue(phonenumber.charAt(0)); and so on
I think an approach with regex here would be the cleanest and easiest solution.
public static boolean valPhoneNumber(String phonenumber){
String regex = "[2-9][0-8][0-9][2-9][02-9][0-29][0-9]{4}";
return phonenumber.matches(regex);
}
You should cast the char variables to integer.
you can try this:
int a = Integer.parseInt(phonenumber.substring(0,1));
I added single quotes to check the range. Thank you all.
public static boolean valPhoneNumber(String phonenumber) {
boolean result= true;
if (phonenumber.length() != 10) {
result = false;
} else {
//phonenumber.length();
char a = phonenumber.charAt(0);
char b = phonenumber.charAt(1);
char d = phonenumber.charAt(3);
char e = phonenumber.charAt(4);
char f = phonenumber.charAt(5);
if (a < '2' || a > '9') {
} else if( b<'0' || b>'8') {
result = false;
} else if (d < '2' || d > '9') {
result = false;
} else if (e == '1' && f == '1') {
result = false;
}
}
return result;
}

How to use variables in stack?

I'm trying to write a calc program that finds the infix. In addition the user will input numbers for the x variable and the program will solve it. My program works but it only solves it the first time. The following times it gives the same answer as the first time.
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
class Stack {
char a[] = new char[100];
int top = -1;
void push(char c) {
try {
a[++top] = c;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Stack full , no room to push , size=100");
System.exit(0);
}
}
char pop() {
return a[top--];
}
boolean isEmpty() {
return (top == -1) ? true : false;
}
char peek() {
return a[top];
}
}
public class intopost {
static Stack operators = new Stack();
public static void main(String argv[]) throws IOException {
String infix;
// create an input stream object
BufferedReader keyboard = new BufferedReader(new InputStreamReader(
System.in));
// get input from user
System.out.print("\nEnter the algebraic expression in infix: ");
infix = keyboard.readLine();
String postFx = toPostfix(infix);
// output as postfix
System.out.println("The expression in postfix is:" + postFx);
if (postFx.contains("x")) {
String line = "";
do {
System.out.println("Enter value of X : ");
line = keyboard.readLine();
if (!"q".equalsIgnoreCase(line)) {
postFx = postFx.replaceAll("x", line);
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
}
} while (!line.equals("q"));
} else {
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
}
}
private static String toPostfix(String infix)
// converts an infix expression to postfix
{
char symbol;
String postfix = "";
for (int i = 0; i < infix.length(); ++i)
// while there is input to be read
{
symbol = infix.charAt(i);
// if it's an operand, add it to the string
if (symbol != ' ') {
if (Character.isLetter(symbol) || Character.isDigit(symbol))
postfix = postfix + " " + symbol;
else if (symbol == '(')
// push (
{
operators.push(symbol);
} else if (symbol == ')')
// push everything back to (
{
while (operators.peek() != '(') {
postfix = postfix + " " + operators.pop();
}
operators.pop(); // remove '('
} else
// print operators occurring before it that have greater
// precedence
{
while (!operators.isEmpty() && !(operators.peek() == '(')
&& prec(symbol) <= prec(operators.peek()))
postfix = postfix + " " + operators.pop();
operators.push(symbol);
}
}
}
while (!operators.isEmpty())
postfix = postfix + " " + operators.pop();
return postfix.trim();
}
static int prec(char x) {
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' || x == '%')
return 2;
return 0;
}
}
class EvaluateString {
public static int evaluate(String expression) {
char[] tokens = expression.toCharArray();
// Stack for numbers: 'values'
LinkedList<Integer> values = new LinkedList<Integer>();
// Stack for Operators: 'ops'
LinkedList<Character> ops = new LinkedList<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.isEmpty() && 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.isEmpty())
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;
}
There is a mistake inside while loop in main method. See snippet below.
postFx = postFx.replaceAll("x", line);
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx));
Here postFx = postFx.replaceAll("x", line); you lost reference to postfix form that contains variable x. Subsequent calls of replaceAll doesn't have any effect. So expression with first entered value is evaluated.
You can easily fix it by replacing code above with
System.out.println("Answer to expression : "
+ EvaluateString.evaluate(postFx.replaceAll("x", line)));

Arithmetic calculation for BODMAS in Java

I have written this code for Bodmas, but getting some error in this. If I do 3-5+9, it will result in 3.04.0.
It just start concatenating, though it works for all other operations like *, / and -, please help.
public static String calculation(BODMASCalculation bodmas, String result) {
while (bodmas.hasMatch()) {
double value, leftOfOperator = bodmas.getLeft();
char op = bodmas.getOperator();
double rightOfOprator = bodmas.getRight();
switch (op) {
case '/':
if(rightOfOprator == 0) //Divide by 0 generates Infinity
value = 0;
else
value = leftOfOperator / rightOfOprator;
break;
case '*':
value = leftOfOperator * rightOfOprator;
break;
case '+':
value = leftOfOperator + rightOfOprator;
break;
case '-':
value = leftOfOperator - rightOfOprator;
break;
default:
throw new IllegalArgumentException("Unknown operator.");
}
result = result.substring(0, bodmas.getStart()) + value + result.substring(bodmas.getEnd());
bodmas = new BODMASCalculation(result);
}
return result;
}
Another function is:-
public boolean getMatchFor(String text, char operator) {
String regex = "(-?[\\d\\.]+)(\\x)(-?[\\d\\.]+)";
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile(regex.replace('x', operator)).matcher(text);
if (matcher.find()) {
this.leftOfOperator = Double.parseDouble(matcher.group(1));
this.op = matcher.group(2).charAt(0);
this.rightOfOprator = Double.parseDouble(matcher.group(3));
this.start = matcher.start();
this.end = matcher.end();
return true;
}
return false;
}
I have a solution by adding
String sss = null;
if(op == '+' && !Str.isBlank(result.substring(0, bodmas.getStart())) && value >= 0)
sss = "+";
else
sss = "";
result = result.substring(0, bodmas.getStart()) + sss + value + result.substring(bodmas.getEnd());
But don't want to do that, I want this to work for all the operators.
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)
{
System.out.println(EvaluateString.evaluate("10 + 2 * 6"));
System.out.println(EvaluateString.evaluate("100 * 2 + 12"));
System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 )"));
System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 ) / 14"));
}
}
The Java Scripting API allows you to pass parameters from Java application to the script engine and vice versa.
You can use Javax ScriptEngine to pass values from your app to a script.
And using it's eval() method, you can give it a mathematical expression in the form of a string and it will do the the math for you... (Handles BODMAS too).
Example:
ScriptEngineManager mgr = new.ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2/3*45";
System.out.println(engine.eval(foo));
Outputs: 70
Include the following imports , if the IDE doesn't suggest them :
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
Check the documentation here ScriptEngine
I hope it helps.
The solution can be achieved by using the shunting yard algorithm. We start by creating an infix notation of the equation then follows the postfix notation. Here is a description of the algorithm https://en.wikipedia.org/wiki/Shunting_yard_algorithm. This solution solves for any nested number of brackets on the string expression.
public static double evaluate(String exp) {
char[] tokens = exp.toCharArray();
Queue<Object> values = new LinkedList<>();
// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();
for (int i = 0; i < tokens.length; i++) {
//infix
// Current token is a whitespace, skip it
if (tokens[i] == ' ') {
continue;
}
// Current token is a number, push it to stack for numbers
else 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]);
if ((i+1)<tokens.length &&tokens[i + 1] >= '0' && tokens[i + 1] <= '9') {
i++;
} else {
break;
}
}
values.add(Double.parseDouble(sbuf.toString()));
} else if (tokens[i] == '*' || tokens[i] == '-' || tokens[i] == '/' || tokens[i] == '+') {
if (ops.isEmpty()) {
ops.push(tokens[i]);
continue;
}
char op1 = ops.peek();
boolean hasHighPrecedence = hasPrecedence(op1, tokens[i]);
if (hasHighPrecedence) {
char op = ops.pop();
values.add(op);
ops.push(tokens[i]);
} else {
ops.push(tokens[i]);
}
} else if (tokens[i] == '(') {
ops.push(tokens[i]);
} else if (tokens[i] == ')') {
while (ops.peek() != '(') {
values.add(ops.pop());
}
ops.pop();
}
}
while (!ops.isEmpty()) {
values.add(ops.pop());
}
//post fix
Stack<Double> numStack = new Stack<>();
while (!values.isEmpty()) {
Object val = values.poll();
if (val instanceof Character) {
char v = (Character) val;
if (v == '*' || v == '-' || v == '/' || v == '+') {
double num2, num1;
num1 = numStack.pop();
num2 = numStack.pop();
double ans = applyOp(v, num1, num2);
numStack.push(ans);
}
} else {
double num = (double) val;
numStack.push(num);
}
}
return numStack.pop();
}
public static double applyOp(char op, double b, double a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
IllegalArgumentException("Cannot divide by zero");
return a / b;
}
return 0;
}
public static boolean hasPrecedence(char op1, char op2) {
if (op1 == '*' && op2 == '/') {
return false;
} else if (op1 == '/' && op2 == '*') {
return true;
} else if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return true;
} else if (op1 == '+' && op2 == '-') {
return true;
} else {
return false;
}
}
"BODMAS" is a not very operational rule. Especially addition and subtraction have the same precedence and are calculated from left to right 1-2+3-4+5 = (((1-2)+3)-4)+5.
The rule is for a nested loop.
Loop
replaceAll ( number ) --> number
replaceAll number `[*/]' number --> number op number
replaceAll number `[+-]' number --> number op number
Until nothing is replaced.
This ensures that 3-4/26+5 -2-> 3-26+5 -2-> 3-12+5 -3-> -9+5 -3-> -4

Categories