Today, I am studying the stack and queue in Chapter 4. I tried to compile a small program with matching parentheses. In the past, when I was in my sophomore year, when I learned the data structure, the teacher asked me to compile such a program, but at that time it was a C language. I feel that I have a certain understanding of object-oriented, and it takes more than two hours to complete the compilation and debugging. In the past, it seems that I spent almost all night.
However, I feel that my abilities still need to be improved.
The Code is as follows:
Import java. util .*;
Public class stacktest {
Public static void main (string ARGs []) {
// Enter the detection variable and create necessary parameters
System. Out. println ("input :");
Pipeline SC = new pipeline (system. In );
String word = SC. Next ();
Int size = word. Length (); // The maximum value of size. All input values may be in parentheses.
Stack stack = new stack (size );
Bracketchecker bracket = new bracketchecker ();
// Stack entry
For (INT I = 0; I <size; I ++ ){
Bracket. setinput (word. charat (I ));
If (bracket. checktype ()){
If (bracket. checkpush () stack. Push (bracket. Input );
Else
If (bracket. checkpop (stack. Peek () stack. Pop ();
Else {
System. Out. println ("error:" + bracket. Input + "at" + I );
System. Exit (-1 );
}
}
}
If (stack. Empty ())
System. Out. println ("correct! ");
Else
System. Out. println ("error! The stack isn' t empty ");
}
}
Class Stack {
Private int maxsize;
Private char [] stackarray;
Private int top;
Stack (INT size ){
This. maxsize = size;
Stackarray = new char [maxsize];
Top =-1;
}
// Output Stack
Public char POP (){
Return (stackarray [top --]);
}
// Stack entry
Public void push (char input ){
Stackarray [++ top] = input;
}
// View
Public char PEEK (){
Return (stackarray [Top]);
}
// Whether it is null
Public Boolean empty (){
Return (Top =-1 );
}
}
Class bracketchecker {
Char input;
Bracketchecker (){
}
// Input parameter input
Public void setinput (char input ){
This. Input = input;
}
// Determine whether it is a stack-related type
Public Boolean checktype (){
Switch (input ){
Case '{':
Case '}':
Case '[':
Case ']':
Case '(':
Case ')': Return true;
Default: Return false;
}
}
// Determine whether to import data to the stack
Public Boolean checkpush (){
Switch (input ){
Case '{':
Case '[':
Case '(': Return true;
Default: Return false;
}
}
// Determine whether a stack exists
Public Boolean checkpop (char lastsymbol ){
If (lastsymbol = '{' & input = '}') return true;
If (lastsymbol = '[' & input = ']') return true;
If (lastsymbol = '(' & input = ') return true;
Return false;
}
}