I am trying to make a java class that allow the user to put in space when putting in the tokens for the calculator and then turns it into postfix.
But it is not giving the correct output. For example, for an input of 1+2, the output should be 12+ but it is 12.
import java.util.*;
public class Infix
{
Stack loco = new Stack();
//create a scanner
//now to create a stack
public String Prefix(String gordo)
{
//Here is where the Program Begin
//type the the regular expression
String[] red;
red=gordo.split("(?=[()+\\-*/])|(?<=[()+\\-*/])"); //tokenize the string include delimiter
System.out.println("THE EXPRESSION IN INFIX IS");
for(int k=0;i<red.length;k++)
{
red[i]=red[i].trim(); //remove white spaces
}
//now we will test out if what is stored is digit or character
System.out.println("BREAKING IT ALL DOWN INTO A STRING OF CHARACTERS");
String ramon;
char[] c; //an array of characters
char feo; // a single character
String post=""; //this is where the post fix expression will be put in
for(int i=0;i<red.length;i++)
{
ramon=red[i];
c=ramon.toCharArray();
for(int j=0;j<c.length;j++)
{
System.out.println(c[j]); //print what is stored in C
feo=c[j];
if(Character.isLetterOrDigit(feo) == true)
{
post=post+feo; //add character to string to post fix
}
else if( feo == '(' )
{
loco.push(feo);
}
else if( feo == ')')
{
char look;
while((look = LookAt()) != '(')
{
post=post+look; //add it all in there
PopIt();
}
}
//this does the associtivity and the operator precdence
//if the operator is lower or equal to the precedence change
//the current operand pop it from stack and put it into output
//string
else
{
while(LaPrio(feo) <= LaPrio(LookAt()))
{
post=post+LookAt();
PopIt();
}
}
}
}
System.out.println("THIS IS THE POSTFIX EXPRESSION");
return post;
}
//this will determine operator precedence
private int LaPrio(char operator)
{
if(operator == '/' || operator == '*' || operator == '%')
{
return 2;
}
if(operator == '+' || operator == '-')
{
return 1;
}
return 0;
}
//this will do the see what is one top of the stack
private Character LookAt()
{
if( !loco.empty() == false) //if there no items it will return false plus ! make it true
{
return(Character) loco.peek();
}
else
return 0;
}
private void PopIt()
{
if(!loco.empty())
{
loco.pop();
}
}
}
Related
I'm trying to solidify my understanding of stacks and operators by creating a simple calculator to process arithmetic expressions that involve parentheses. I feel like I have code that should work, but it's most certainly not giving me the right output.
Even though I have a method to evaluate each expression, when I try to return the number stack it does not print out any evaluated method but only all numbers inputted by the user. I want to deal with issues in input like mismatched operators or missing parentheses as well.
I attempt to run the code with simple expressions like 9 * 5 or something like (7 * 6) + (9 - 4) and it just returns the last double regardless.
Here's my code so far:
Main method
import java.util.Stack;
import javax.swing.JOptionPane;
public class Calculator {
// instance variables
private Stack < Double > nums;
private Stack < String > ops;
String list;
// constructor
public Calculator()
{
nums = new Stack < Double > ();
ops = new Stack < String > ();
}
// methods
public static boolean isDouble(String str) {
try {
Double.parseDouble(str);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
public static boolean isValidOp(String str) {
return (str == "(" || str == ")" || str == "^" || str == "*" || str == "/" || str == "+" || str == "-");
}
public int prec(String str) {
if (str == "(" || str == ")")
return 4;
if (str == "^")
return 3;
if (str == "*" || str == "/")
return 2;
if (str == "+" || str == "-")
return 1;
else
return -1;
}
public double applyOperator(double left, String op, double right) {
if (op == "+") {
return (left + right);
}
if (op == "-") {
return (left - right);
}
if (op == "*") {
return (left * right);
}
if (op == "/") {
return (left / right);
}
if (op == "^") {
return Math.pow(left, right);
} else {
throw new IllegalArgumentException("Not a valid operator");
}
}
public String evaluate(String str)
{
String [] tokens = str.split(" ");
for (int i = 0; i < tokens.length; i++)
{
if (isDouble(tokens [i]) == true)
{
nums.push(Double.parseDouble(tokens [i]));
}
if (tokens [i] == "(")
{
ops.push(tokens [i]);
}
if (tokens [i] == ")")
{
String op1 = ops.pop();
double num1 = nums.pop();
double num2 = nums.pop();
double result = applyOperator(num1,op1,num2);
nums.add(result);
}
if (tokens [i] == "+" || tokens [i] == "-" || tokens [i] == "*" || tokens [i] == "/" || tokens [i] == "^")
{
if(ops.isEmpty())
{
ops.push(tokens [i]);
}
else if (prec(tokens [i]) > prec(ops.peek()))
{
ops.push(tokens [i]);
}
else if (prec(tokens [i]) < prec(ops.peek()) && !ops.isEmpty() && ops.peek() != "(")
{
String ac1 = ops.pop();
double res1 = nums.pop();
double res2 = nums.pop();
double outcome = applyOperator(res1,ac1,res2);
nums.add(outcome);
}
}
}
while(!ops.isEmpty() && nums.size() > 1)
{
String ab = ops.pop();
double bb = nums.pop();
double cb = nums.pop();
double clac = applyOperator(bb,ab,cb);
nums.add(clac);
}
String fix = nums.pop().toString();
return fix;
}
}
Tester:
import javax.swing.JOptionPane;
public class AppforCalc {
public static void main(String [] args)
{
Calculator calc = new Calculator();
String reply = "yes";
String instructions = "Enter a mathematical expression. Separate everything with spaces";
while(reply.equalsIgnoreCase("yes"))
{
String expression = JOptionPane.showInputDialog(instructions);
String ans = calc.evaluate(expression);
reply = JOptionPane.showInputDialog("The solution is " + ans + "Try again?");
}
}
}
The main reason you algorithm fails is due to using == when trying to check for String equality.
In Java, == is a boolean operator which behaves identically for all operands, and checks the equality of the values of the operands. This means that primitives are checked as one might expect, but Strings, which are objects, will result in comparing the memory references of the two Strings, which will result in true only if the two Strings are actually the same String. This means that String equality checks must be done with the equals method.
There are more issues with the behavior of the calculator (algorithmic ones), but those will be easier to identify and fix after handling the String equality checks. One example of an issue that must be fixed is:
while(!ops.isEmpty() && nums.size() > 1)
{
String ab = ops.pop();
double bb = nums.pop();
double cb = nums.pop();
double clac = applyOperator(bb,ab,cb);
nums.add(clac);
}
The operands (bb and cb) are popped from a Stack, therefore they arrive in a reveresed order (when parsed, cb was pushed into the stack before bb). This means that cb is the leftside operand and bb is the rightside operand -> double clac = applyOperator(cb,ab,bb); The same refactoring should be done for all usages of the applyOperand method.
Another issue is the following:
else if (prec(tokens [i]) < prec(ops.peek()) && !ops.isEmpty() && ops.peek() != "(")
{
String ac1 = ops.pop();
double res1 = nums.pop();
double res2 = nums.pop();
double outcome = applyOperator(res1,ac1,res2);
nums.add(outcome);
}
An internal evaluation was made, but the triggering of the evaluation is the discvery of an operand with a lower presendence. The operand should be pushed into the operations stack after the evaluation:
else if (prec(tokens [i]) < prec(ops.peek()) && !ops.isEmpty() && ops.peek() != "(")
{
...
...
nums.add(outcome); // I highly suggest refactoring this to nums.push due to readability considerations
ops.push(tokens[i]);
}
References:
The difference between == and equals in Java
Guide for implementing a scientific calculator (in c++, use as an algorithmic reference)
The Shunting Yard Algorithm - As suggested by user207421
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)));
My Java Program is below. It's my training exercise. The one implements stack stucture for special type of string parsing(string with delimiter).
This delimiter-matching program works by reading characters from the string one at
a time and placing opening delimiters when it finds them, on a stack. When it reads
a closing delimiter from the input, it pops the opening delimiter from the top of the
stack and attempts to match it with the closing delimiter. If they’re not the same
type (there’s an opening brace but a closing parenthesis, for example), an error
occurs. Also, if there is no opening delimiter on the stack to match a closing one, or
if a delimiter has not been matched, an error occurs. A delimiter that hasn’t been
matched is discovered because it remains on the stack after all the characters in the
string have been read.
I use Eclipse. My output is here:
Please enter String:
{}
ch0 = {
ch1 = }
chLabel1 = **UNDEFINED CHAR(SQUARE WITH QUESTION MARK INSIDE IT)**
Error at }**
Could you explain value of chLabel?
As I understand operator "|" (here, cause two operands have boolean type) - is "lazy", shortcut version of "||" operator. I've tested the program after substitution "|" for "||"-result is the same.
public class MyStack {
private int top=0;
private int maxSize=0;
private char[] charArray=null;
public MyStack(int size){
maxSize=size;
top=0;
charArray=new char[maxSize];
}
public void push(char ch){
charArray[top++]=ch;
}
public char pop(){
return charArray[top--];
}
public boolean isEmpty(){
if(top==0)
return true;
else return false;
}
public boolean isFull(){
if(top==(maxSize-1))
return true;
else return false;
}
}
class StringParse {
private String stringForParsing = null;
public StringParse(String string) {
this.stringForParsing = string;
}
public void parser() {
char[] chArr = stringForParsing.toCharArray();
MyStack mySt = new MyStack(chArr.length);
for (int i = 0; i < chArr.length; i++) {
char ch = chArr[i];
switch (ch) {
case '{':
case '(':
case '[':
mySt.push(ch);
System.out.println("ch" + i + " = " + ch);
break;
case '}':
case ')':
case ']':
if (mySt.isEmpty())
System.out.println("Error at" + ch);
else {
char chLabel = mySt.pop();
System.out.println("ch" + i + " = " + ch);
System.out.println("chLabel" + i + " = " + chLabel);
if ((chLabel == '{') && (ch == '}') | (chLabel == '(') && (ch == ')') | (chLabel == '[') && (ch == ']'))
break;
else {
System.out.println("Error at " + ch);
break;
} // end of second else
} //end of first else
default:
break;
} //end of switch
} //end of parser method
}
} //end of class
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
System.out.println("Please enter String:");
String s = br.readLine();
StringParse strP = new StringParse(s);
strP.parser();
}
}
There are two problems:
There's an error with the pop function.
Consider doing one push and then one pop:
top = 0
push
insert at position 0
set top to 1
pop
get position 1 (not set yet!)
set top to 0
You need to use pre-decrement instead of post-decrement, so charArray[top--] should be charArray[--top].
With this change I get chLabel1 = {.
Reiterating what I said in the comments...
| has higher precendence than &&(as opposed to || which has lower precedence) (see this),
thus a && b | c && d is the same as a && (b | c) && d,
as opposed to a && b || c && d which would be (a && b) || (c && d).
When changing the |'s to ||'s, I no longer get Error at }.
There may be a problem with your MyStack class
Using java.util.Stack gives me no error, just a "chLabel1 = {"
Error at } can be resolved by following Dukeling's advice and using || instead of |:
(chLabel == '{') && (ch == '}') || (chLabel == '(') && (ch == ')') || (chLabel == '[') && (ch == ']')
So, it looks like your code in MyStack.pop() doesn't return a valid char. I'll need to see your MyStack code to help further.
I have a method that checks to see if an equation written is correct.
This method check for:
Multiple Parentheses
Excess operators
Double Digits
q's
and any character in a string that is not and of these:
.
private static final String operators = "-+/*%_";
private static final String operands = "0123456789x";
It was working fine, but then I added in modular to the operators and now whenever my code reaches the part in the method that checks to the left and the right of an operand to see if it is neither the end of the string or the beginning I get an error saying
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
My method and all it's additional methods.
private static final String operators = "-+/*%_";
private static final String operands = "0123456789x";
public Boolean errorChecker(String infixExpr)
{
char[] chars = infixExpr.toCharArray();
StringBuilder out = new StringBuilder();
for (int i = 0; i<chars.length; i++)
{
System.out.print(infixExpr.charAt(i));
if (isOperator(infixExpr.charAt(i)))
{
if (i == 0 || i == infixExpr.length())
{
out.append(infixExpr.charAt(i));
}
else if (isOperator(infixExpr.charAt(i + 1)) && isOperator(infixExpr.charAt(i - 1)))
{
System.out.println("To many Operators.");
return false;
}
else if (isOperator(infixExpr.charAt(i + 1)))
{
if (infixExpr.charAt(i) != '-' || infixExpr.charAt(i + 1) != '-')
{
System.out.println("To many Operators.");
return false;
}
}
else if (isOperator(infixExpr.charAt(i - 1)))
{
if (infixExpr.charAt(i) != '-' || infixExpr.charAt(i - 1) != '-')
{
System.out.println("To many Operators.");
return false;
}
}
}
else if (isOperand(infixExpr.charAt(i)))
{
if (i == 0 || i == infixExpr.length())
{
out.append(infixExpr.charAt(i));
}//THE LINE RIGHT BELOW THIS COMMENT THROWS THE ERROR!!!!!
else if (isOperand(infixExpr.charAt(i + 1)) || isOperand(infixExpr.charAt(i - 1)))
{
System.out.println("Double digits and Postfix form are not accepted.");
return false;
}
}
else if (infixExpr.charAt(i) == 'q')
{
System.out.println("Your meow is now false. Good-bye.");
System.exit(1);
}
else if(infixExpr.charAt(i) == '(' || infixExpr.charAt(i) == ')')
{
int p1 = 0;
int p2 = 0;
for (int p = 0; p<chars.length; p++)
{
if(infixExpr.charAt(p) == '(')
{
p1++;
}
if(infixExpr.charAt(p) == ')')
{
p2++;
}
}
if(p1 != p2)
{
System.out.println("To many parentheses.");
return false;
}
}
else
{
System.out.println("You have entered an invalid character.");
return false;
}
out.append(infixExpr.charAt(i));
}
return true;
}
private boolean isOperator(char val)
{
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val)
{
return operands.indexOf(val) >= 0;
}
My main portion that runs the method:
Boolean meow = true;
while(meow)
{
System.out.print("Enter infix expression: ");
infixExpr = scan.next();//THE LINE RIGHT BELOW THIS COMMENT THROWS THE ERROR!!!!!
if(makePostfix.errorChecker(infixExpr) == true)
{
System.out.println("Converted expressions: "
+ makePostfix.convert2Postfix(infixExpr));
meow = false;
}
}
It was working fine before, but now it won't even pass 1+2 which was previously working and I changed NONE of that you see. What's wrong!?!?
What looks like what's happening is that you check for the character at index (i + 1) several times in your code. Lets say you input a string with a length of five characters. The program goes through and reaches the line:
else if (isOperator(infixExpr.charAt(i + 1)) && isOperator(infixExpr.charAt(i - 1)))
If i == 4, this will cause the code:
infixExpr.charAt(i + 1)
to throw an index error.
In essance, you're checking for a character at index five (the sixth character) in a string with a maximum index index of four which is five characters in length. Also, your checking for
if(i==0 || i == infixExpr.length)
won't work as is. Maybe check for (i==infixExpr.length-1).
I'm supposed to create a Java program which reads expressions that contain, among other items, braces { },
brackets [ ], and parentheses ( ). My program should be properly
nested and that ‘(‘ matches ‘)’, ‘[‘ matches ‘]’, and ‘{’ matches ‘}‘ The
program should be terminated by a ‘$’ at the beginning of an input line.
These are supposed to be sample runs of my program:
Enter an Expression:
A[F + X {Y – 2}]
The expression is Legal
Enter an Expression:
B+[3 – {X/2})*19 + 2/(X – 7)
ERROR—‘]’ expected
Enter an Expression:
()) (
ERROR--‘)’ without ‘(‘
$
I created a class called BalancedExpression and a driver called ExpressionChecker.
I completed my BalancedExpression class. But, I'm having trouble setting up my driver to print out an expression using an InputStreamReader and a BufferedReader. The only thing I was able to figure out was how to terminate my program by letting the user enter a $.
Here is my code so far:
Balanced Expression class:
public class BalancedExpression
{
public BalancedExpression() // Default Constructor
{
sp = 0; // the stack pointer
theStack = new int[MAX_STACK_SIZE];
}
public void push(int value) // Method to push an expression into the stack
{
if (!full())
theStack[sp++] = value;
}
public int pop() // Method to pop an expression out of the stack
{
if (!empty())
return theStack[--sp];
else
return -1;
}
public boolean full() // Method to determine if the stack is full
{
if (sp == MAX_STACK_SIZE)
return true;
else
return false;
}
public boolean empty() // Method to determine if the stack is empty
{
if (sp == 0)
return true;
else
return false;
}
public static boolean checkExpression(String ex) // Method to check Expression in stack
{
BalancedExpression stExpression = new BalancedExpression();
for(int i = 0; i< MAX_STACK_SIZE; i++)
{
char ch = ex.charAt(i);
if(ch == '(' || ch == '{' || ch == '[')
stExpression.push(ch);
else if(ch == ')' && !stExpression.empty() && stExpression.equals('('))
stExpression.pop();
else if(ch == '}' && !stExpression.empty() && stExpression.equals('{'))
stExpression.pop();
else if(ch == ']' && !stExpression.empty() && stExpression.equals('['))
stExpression.pop();
else if(ch == ')' || ch == '}' || ch == ']' )
return false;
}
if(!stExpression.empty())
return false;
return true;
}
private int sp;
private int[] theStack;
private static final int MAX_STACK_SIZE = 6;
}// End of class BalancedExpression
My Driver Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExpressionChecker
{
public static void main(String[] args)
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
BalancedExpression exp = new BalancedExpression();
String expression = "";
do
{
try{
System.out.print("Enter an Expression: ");
expression = console.readLine();
if("$".equals(expression))
break;
}catch(Exception e){
System.out.println("IO error:" + e);
}
}while(!expression.equals(""));// End of while loop
}
}// End of class ExpressionChecker
Can anyone please help me develop my driver program to print out an output similar to the sample example?
Any help is appreciated. Thanks!
In the if statements in checkExpression method you are using
stExpression.equals()
while what you want to do is to 'peek' at the value on the top of the stack.
Adding simple method that pops the value, pushes it back and returns it should solve the problem(at least this part).
Here is a very short example where you can do the above check very easily :) We have Stack class in Java, it will make the program very easy. Please find below the simple code for this question:
package com.test;
import java.util.Scanner;
import java.util.Stack;
public class StackChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enete an expression : ");
String expr = sc.nextLine();
if(checkvalidExpression(expr)){
System.out.println("The Expression '"+expr+"' is a valid expression!!!");
}
else{
System.out.println("The Expression '"+expr+"' is a NOT a valid expression!!!");
}
}
public static boolean checkvalidExpression(String expr){
Stack<Character> charStack = new Stack<Character>();
int len = expr.length();
char exprChar = ' ';
for(int indexOfExpr = 0; indexOfExpr<len; indexOfExpr++){
exprChar = expr.charAt(indexOfExpr);
if(exprChar == '(' || exprChar == '{' || exprChar == '['){
charStack.push(exprChar);
}
else if(exprChar == ')' && !charStack.empty()){
if(charStack.peek() == '('){
charStack.pop();
}
}
else if(exprChar == '}' && !charStack.empty()){
if(charStack.peek() == '{'){
charStack.pop();
}
}
else if(exprChar == ']' && !charStack.empty()){
if(charStack.peek() == '['){
charStack.pop();
}
}
else if(exprChar == ')' || exprChar == '}' || exprChar == ']' ){
return false;
}
}
if(!charStack.empty())
return false;
return true;
}
}