11package chap4_Stacks_Queues ;
22
3- class StackX {
3+ import java .io .BufferedReader ;
4+ import java .io .IOException ;
5+ import java .io .InputStreamReader ;
6+
7+ class StackY {
48 private int maxSize ;
59 private char [] stackArray ;
610 private int top ;
711
8- public StackX (int s ) {
12+ public StackY (int s ) {
913 maxSize = s ;
1014 stackArray = new char [maxSize ];
1115 top = -1 ;
@@ -30,7 +34,7 @@ public boolean isEmpty() {
3034 public boolean isFull () {
3135 return (top == maxSize );
3236 }
33- } //end class StackX
37+ } //end class StackY
3438
3539class BracketChecker {
3640 private String input ;
@@ -41,7 +45,7 @@ public BracketChecker(String in) {
4145
4246 public void check () {
4347 int stackSize = input .length ();
44- StackX theStack = new StackX (stackSize );
48+ StackY theStack = new StackY (stackSize );
4549
4650 for (int j = 0 ; j < input .length (); j ++) {
4751 char ch = input .charAt (j );
@@ -54,29 +58,57 @@ public void check() {
5458 case '}' :
5559 case ']' :
5660 case ')' :
57- if (!theStack .isEmpty ()) {
61+ if (!theStack .isEmpty ()) { //第一个错误是准确的 但会pop一个正常的导致后面匹配错误
5862 char chx = theStack .pop ();
5963 if (chx == '{' && ch !='}' ||
6064 chx == '[' && ch != ']' ||
6165 chx == '(' && ch != ')' ) {
6266 System .out .println ("Error: " + ch + " at " + j );
67+ break ;
6368 }
6469 }else {
6570 System .out .println ("Error: " + ch + " at " + j );
6671 }
6772 break ;
6873 default :
6974 break ;
70- }e
75+ } //end switch
76+ } //end for
77+ if (!theStack .isEmpty ()) {
78+ System .out .println ("Error: missing right dilimiter" );
7179 }
72- }
80+ } //end checker
7381}
7482
7583public class BracketApp {
7684
77- public static void main (String [] args ) {
85+ public static void main (String [] args ) throws IOException {
7886 // TODO Auto-generated method stub
79-
87+ String input ;
88+ while (true ) {
89+ System .out .println ("Enter string containing delimiters: " );
90+ System .out .flush ();
91+ input = getString ();
92+ if (input .equals ("" )) {
93+ break ;
94+ }
95+ BracketChecker theChecker = new BracketChecker (input );
96+ theChecker .check ();
97+ }
98+ }
99+
100+ public static String getString () throws IOException {
101+ InputStreamReader isr = new InputStreamReader (System .in );
102+ BufferedReader br = new BufferedReader (isr );
103+ String s = br .readLine ();
104+ return s ;
80105 }
81106
82107}
108+
109+
110+
111+
112+
113+
114+
0 commit comments