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;
}
}
Related
I have the following code for the solution of Hackerrank.
public static void main(String[] args) {
System.out.println(isBalanced("{(([])[])[]}"));
}
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
} else {
stack.push(c);
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Although the code seems to working without any problem, it throws the following error on the Hackerrank page. I already test the input in my local IDE as it is {(([])[])[]}, but I am not sure if I need to get the last element (it maybe due to getting it via Character cStack = stack.peek(); and then stack.pop();.
So, could you please have a look at and test this code on Hackerrank page and let me know what is wrong?
Update:
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else if (stack != null) {
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
}
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Before calling stack.peek(), you need to check if the stack is empty or not. Calling pop() or peek() on an empty stack will raise an error.
If the current character is an opening bracket, you don't even need to check the stack top. If it is a closing bracket, then check if the stack is empty or not first. If it is, return false. Otherwise compare the top character and make a decision.
I took a half a year off from programming and now Im just refreshing my memory w super basic little interview questions...and Ive been stuck for 2 days on the first one.. Below is my code can someone just hint to me why the program shows no errors but upon compilation does nothing? It should ignore text characters but Im not even there yet
public class bracketCheck {
public static void main(String[] args) {
Stack <Character> s = new <Character> Stack();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
int count = 0;
boolean cont = true;
Character stackTop;
Character current = buff.charAt(count);
do {
if(current == ')' || current== '}' || current== ']') {
s.push(current);
count++;
}
else if(current== '(' || current== '{' || current== '[') {
stackTop = s.pop();
cont = match(stackTop, current);
}
}
while(s.isEmpty() == false /*&& cont =true*/);
if(s.isEmpty())
System.out.println("bout time......");
}
private static boolean match(Character top , Character not) {
if(top == ')' && not == '(')
return true;
else if(top == ']' && not == '[')
return true;
else if(top == '}' && not == '{')
return true;
else
return false;
}
}
I saw some issues in your code, this is my fixed version of it
import java.util.Scanner;
import java.util.Stack;
// use Capital letters in the beginning of class names
public class BracketCheck {
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
// using java8 makes iterating over the characters of a string easier
buff.chars().forEach(current -> {
// if <current> is an opening bracket, push it to stack
if (current == '(' || current == '{' || current == '[') {
stack.push((char) current);
}
// if <current> is a closing bracket, make sure it is matching an opening
// bracket or alert and return
else if (current == ')' || current == '}' || current == ']') {
if (!match(stack, (char) current)) {
System.out.println("no good");
return;
}
}
});
// if, after we finished iterating the string, stack is empty, all opening
// brackets had matching closing brackets
if (stack.isEmpty()) {
System.out.println("bout time......");
}
// otherwise, alert
else {
System.out.println("woah");
}
}
private static boolean match(Stack<Character> stack, Character closer) {
// if stack is empty, the closer has no matching opener
if (stack.isEmpty()) {
return false;
} else {
// get the most recent opener and verify it matches the closer
Character opener = stack.pop();
if (opener == '(' && closer == ')')
return true;
else if (opener == '[' && closer == ']')
return true;
else if (opener == '{' && closer == '}')
return true;
else
return false;
}
}
}
I am getting the NullPointerException in the following code at the line s.push(expr.charAt(i)) in the function areParenthesisBalanced. Please help me understand why is it so?
Is it because stack object is initialised to null?
public class BalancedParenthesisUsingStack {
static Boolean ArePair(char opening, char closing){
if(opening =='(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
static Boolean areParenthesisBalanced(String expr){
Stack<Character> s = null;
for(int i =0; i<expr.length();i++){
Character c = expr.charAt(i);
if(expr.charAt(i)=='(' || expr.charAt(i)=='[' || expr.charAt(i)=='{'){
s.push(expr.charAt(i));
}
else if (expr.charAt(i)==')' || expr.charAt(i)==']' || expr.charAt(i)=='}'){
if(s.isEmpty() || (!ArePair(s.peek(), expr.charAt(i)))){
return false;
}
else
s.pop();
}
}
return s.empty()? true: false;
}
public static void main(String[] args){
String expression;
System.out.println("Enter an expression: "); // input expression from STDIN/Console
Scanner v = new Scanner(System.in);
expression = v.nextLine();
if(areParenthesisBalanced(expression))
System.out.println("Balanced\n");
else
System.out.println("Not Balanced\n");
}
}
Exception : Enter an expression:
{f[f]d}
Exception in thread "main" java.lang.NullPointerException
at com.practitcePrograms.BalancedParenthesisUsingStack.areParenthesisBalanced(BalancedParenthesisUsingStack.java:22)
at com.practitcePrograms.BalancedParenthesisUsingStack.main(BalancedParenthesisUsingStack.java:41)
You forgot to instantiate the Stack :
Stack<Character> s = new Stack<>;
For your question:
Is it because stack object is initialised to null?
Answer: Yes.
You have to create instance before you use.
Create new instance using
Stack<Character> s = new Stack<>;
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();
}
}
}
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.