CS 1723 -- Check for Balanced Parens
Here is a simple program that uses the Java Stack
class to check for balanced parens.
// SimpleParens: make use of the a simple stack of chars
// Check for matching parens
import java.util.*;
public class SimpleParens {
public static void main(String[] args) {
Stack s = new Stack(); // create a stack
GetData getData = new GetData(); // create input class
// push non-blank chars. Interested only in ()
char ch = getData.getNextNonBlank();
Character chWrap = new Character(ch); // must wrap char to push
char stackCh;
while (ch != 65535) { // as byte this is -1
if (ch == '(') {
chWrap = new Character(ch);
s.push(chWrap);
}
else if (ch == ')') {
if (s.empty()) error();
chWrap = (Character)s.pop();
stackCh = chWrap.charValue();
if (stackCh != '(') error();
}
else error();
ch = getData.getNextNonBlank();
}
if (!s.empty()) error();
System.out.println("Balanced parens");
}
private static void error() {
System.out.println("Error: unbalanced parens");
System.exit(1);
}
}
// GetData: fetch next char
import java.io.*;
public class GetData {
private Reader in; // internal file name for input stream
// GetData: constructor
public GetData () {
in = new InputStreamReader(System.in);
}
// getNextChar: fetches next char
private char getNextChar() {
char ch = ' '; // = ' ' to keep compiler happy
try {
ch = (char)in.read();
} catch (IOException e) {
System.out.println("Exception reading character");
}
return ch;
}
// getNextNonBlank: fetch next non-whitespace char
public char getNextNonBlank() {
char ch = getNextChar();
while (ch == ' ' || ch == '\n')
ch = getNextChar();
return ch;
}
}
Sample run.
% java SimpleParens
( ( ( ) ( () ) () ) () )
Balanced parens
% java SimpleParens
( ( ) ) )
Error: unbalanced parens
% java SimpleParens
( ( # ) )
Error: unbalanced parens
% java SimpleParens
( ( ( ) ) ( ) )
Balanced parens
% java SimpleParens
( ( ( ) ) ( )
Error: unbalanced parens
Revision date: 2001-09-08.
(Please use ISO
8601, the International Standard.)