First I want to say that I am a Java beginner and this is my 2nd program.
I created a program that will do a symbol balance test, but I need someone to help me print the results to the screen because I am getting a blank output whenever I try to find a way to do it. I am also reading into a file. Any help is appreciated please.
test.txt looks like {{}}
For ex,
{ { } } = the symbols are equally balanced
{ [ { } = the symbols are not equally balanced
I need someone to help me find a way to print the results like
{{}} are equally balanced
or
{[}} are not equally balanced
I tried using this and placing it near the bottom of the program in between the last brackets
Code:while (!s.empty()) { System.out.println(s.pop()); if (failed == true) { System.out.println(" symbols do not match"); } else { System.out.println(" The symbols match"); }
Main Program:
Code:import java.io.* ; public class Stackmain { public Stackmain() { } public static boolean main(String expression) throws IOException { final char LEFT_PARENT = '('; final char RIGHT_PARENT = ')'; final char LEFT_CURLY = '{'; final char RIGHT_CURLY = '}'; final char LEFT_SQUARE = '['; final char RIGHT_SQUARE = ']'; Stack s = new Stack(100); char ch; int i = 0; boolean failed = false; FileInputStream fstream = new FileInputStream("test.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((ch = (char)br.read()) != (char)-1 ) if (!s.full()) { for (i=0; !failed && (i < expression.length( )); i++) { switch (expression.charAt(i)) { case LEFT_PARENT: case LEFT_CURLY: case LEFT_SQUARE: s.push(expression.charAt(i)); break; case RIGHT_PARENT: if (s.empty() || (s.pop() != LEFT_PARENT)) failed = true; break; case RIGHT_CURLY: if (s.empty() || (s.pop() != LEFT_CURLY)) failed = true; break; case RIGHT_SQUARE: if (s.empty() || (s.pop() != LEFT_SQUARE)) failed = true; break; } } } return (s.empty() && !failed); } }
Stack Class
Code:class Stack { private int maxStack; private int emptyStack; private int top; private char[] items; public Stack(int size) { maxStack= size; emptyStack = -1; top = emptyStack; items = new char[maxStack]; } public void push(char c) { items[++top] = c; } public char pop() { return items[top--]; } public boolean full() { return top + 1 == maxStack; } public boolean empty() { return top == emptyStack; } }




Reply With Quote