1
+ /*********************************************************************************
2
+ * (Match grouping symbols) A Java program contains various pairs of grouping *
3
+ * symbols, such as: *
4
+ * *
5
+ * ■ Parentheses: ( and ) *
6
+ * ■ Braces: { and } *
7
+ * ■ Brackets: [ and ] *
8
+ * *
9
+ * Note that the grouping symbols cannot overlap. For example, (a{b)} is illegal. *
10
+ * Write a program to check whether a Java source-code file has correct pairs of *
11
+ * grouping symbols. Pass the source-code file name as a command-line argument. *
12
+ *********************************************************************************/
13
+ import java .io .*;
14
+ import java .util .*;
15
+
16
+ public class Exercise_20_11 {
17
+ public static void main (String []args )throws IOException {
18
+ // Check command-line argument
19
+ if (args .length !=1 ) {
20
+ System .out .println ("Usage: Java Exercise_20_11 Source-codeFileName" );
21
+ System .exit (0 );
22
+ }
23
+
24
+ // Check if file exists
25
+ File file =new File (args [0 ]);
26
+ if (!file .exists ()) {
27
+ System .out .println ("The file " +args [0 ] +" does not exist!" );
28
+ System .exit (1 );
29
+ }
30
+
31
+ // Create a stack
32
+ Stack <Character >symbols =new Stack <>();
33
+
34
+ try (// Create an input stream for file
35
+ Scanner input =new Scanner (file );
36
+ ) {
37
+ // Continuously read chars from input
38
+ while (input .hasNext ()) {
39
+ String line =input .nextLine ();
40
+ for (int i =0 ;i <line .length ();i ++) {
41
+ char ch =line .charAt (i );
42
+ // Push symbols (, {, and [ on to the stack
43
+ if (ch =='(' ||ch =='{' ||ch =='[' ) {
44
+ symbols .push (ch );
45
+ }// Process stack
46
+ else if (ch ==')' ||ch =='}' ||ch ==']' ) {
47
+ processSymbols (symbols ,ch );
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ System .out .println ("The Java source-code " +
54
+ (symbols .isEmpty () ?"has" :"does not have" ) +" correct pairs." );
55
+ }
56
+
57
+ /** Method Matchs grouping symbols */
58
+ private static void processSymbols (
59
+ Stack <Character >stack ,Character ch ) {
60
+ // Remove matching symbols from stack
61
+ if ((stack .peek () =='(' &&ch ==')' ) ||
62
+ (stack .peek () =='[' &&ch ==']' ) ||
63
+ (stack .peek () =='{' &&ch =='}' )) {
64
+ stack .pop ();
65
+ }
66
+ else if ((stack .peek () !='(' &&ch ==')' ) ||
67
+ (stack .peek () !='[' &&ch ==']' ) ||
68
+ (stack .peek () !='{' &&ch =='}' )) {
69
+ System .out .println ("The Java source-code does not have"
70
+ +" correct pairs." );
71
+ System .exit (1 );
72
+ }
73
+ }
74
+ }