SlideShare a Scribd company logo
1 of 3
Download to read offline
(Match grouping symbols) A Java program contains various pairs of grouping symbols, such as:
Parentheses: ( and )
Braces: { and }
Brackets: [ and ]
Note that the grouping symbols cannot overlap. For example, (a{b)} is illegal. Write a program
to check whether a Java source-code file has correct pairs of grouping symbols. Pass the source-
code file name as a command-line argument.
Solution
// GroupingSymbols.java
import java.io.*;
import java.util.*;
public class GroupingSymbols
{
public static void main(String[] args) {
if (args.length != 1)
{
System.out.println("Usage: filename");
System.exit(0);
}
File inputFile = new File(args[0]);
// Check if file exists
if (!inputFile.exists()) {
System.out.println("File does not exist!");
System.exit(1);
}
// Create a stack
Stack charstack = new Stack<>();
// arraylist
ArrayList symbolarray = new ArrayList<>();
// addinng all symbols to collection
Collections.addAll(symbolarray, "(", ")", "{", "}", "[", "]");
try(BufferedReader bf = new BufferedReader(new InputStreamReader(new
FileInputStream(inputFile))))
{
String str;
while ((str = bf.readLine()) != null)
{
for (char character : str.toCharArray())
{
String s = character + "";
int sIndex = symbolarray.indexOf(s);
if (sIndex == -1)
continue;
if (charstack.size() == 0)
{
charstack.push(s);
}
else
{
int lIndex = symbolarray.indexOf(charstack.peek());
if (sIndex - 1 == lIndex)
{
charstack.pop();
}
else
{
if ((lIndex & 1) == 1)
{
System.out.println("ERROR at:" + str);
}
charstack.push(s);
}
}
}
}
}
catch (FileNotFoundException exception)
{
System.out.println("File not found.");
exception.printStackTrace();
}
catch (IOException exception)
{
System.out.println("IO error.");
exception.printStackTrace();
}
}
}

More Related Content

Similar to (Match grouping symbols) A Java program contains various pairs of gr.pdf

Use arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdfUse arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdf
footworld1
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
theodorelove43763
 
JAVAWrite a program that takes a command-line argument representin.pdf
JAVAWrite a program that takes a command-line argument representin.pdfJAVAWrite a program that takes a command-line argument representin.pdf
JAVAWrite a program that takes a command-line argument representin.pdf
jibinsh
 
Java Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfJava Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdf
duttakajal70
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
Eclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTEclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDT
deepakazad
 

Similar to (Match grouping symbols) A Java program contains various pairs of gr.pdf (20)

For this assignment, you will develop starter code. After
For this assignment, you will develop starter code. After For this assignment, you will develop starter code. After
For this assignment, you will develop starter code. After
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
FileHandling.docx
FileHandling.docxFileHandling.docx
FileHandling.docx
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Use arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdfUse arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdf
 
Description 1) Create a Lab2 folder for this project2.docx
Description       1)  Create a Lab2 folder for this project2.docxDescription       1)  Create a Lab2 folder for this project2.docx
Description 1) Create a Lab2 folder for this project2.docx
 
JAVAWrite a program that takes a command-line argument representin.pdf
JAVAWrite a program that takes a command-line argument representin.pdfJAVAWrite a program that takes a command-line argument representin.pdf
JAVAWrite a program that takes a command-line argument representin.pdf
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
04 sorting
04 sorting04 sorting
04 sorting
 
Java Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdfJava Program using RecursionWrite a program that reads in a file .pdf
Java Program using RecursionWrite a program that reads in a file .pdf
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Eclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDTEclipse Day India 2011 - Extending JDT
Eclipse Day India 2011 - Extending JDT
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 

More from wailesalekzydelore94

Write the Java source code necessary to build a solution for EITHER .pdf
Write the Java source code necessary to build a solution for EITHER .pdfWrite the Java source code necessary to build a solution for EITHER .pdf
Write the Java source code necessary to build a solution for EITHER .pdf
wailesalekzydelore94
 
Which type of protein does DNA wrap around so that it can be package.pdf
Which type of protein does DNA wrap around so that it can be package.pdfWhich type of protein does DNA wrap around so that it can be package.pdf
Which type of protein does DNA wrap around so that it can be package.pdf
wailesalekzydelore94
 
select an engineering articlejournal with ethical senerio and justi.pdf
select an engineering articlejournal with ethical senerio and justi.pdfselect an engineering articlejournal with ethical senerio and justi.pdf
select an engineering articlejournal with ethical senerio and justi.pdf
wailesalekzydelore94
 
In the cae below identify the subject matter of the controversy, whe.pdf
In the cae below identify the subject matter of the controversy, whe.pdfIn the cae below identify the subject matter of the controversy, whe.pdf
In the cae below identify the subject matter of the controversy, whe.pdf
wailesalekzydelore94
 
Listed below are the major steps in protein synthesis and some event.pdf
Listed below are the major steps in protein synthesis and some event.pdfListed below are the major steps in protein synthesis and some event.pdf
Listed below are the major steps in protein synthesis and some event.pdf
wailesalekzydelore94
 
1.What are 2nd messengers Give specific examples. How are they used.pdf
1.What are 2nd messengers Give specific examples. How are they used.pdf1.What are 2nd messengers Give specific examples. How are they used.pdf
1.What are 2nd messengers Give specific examples. How are they used.pdf
wailesalekzydelore94
 

More from wailesalekzydelore94 (20)

Can you allow a class to be inherited, but prevent a method from bei.pdf
Can you allow a class to be inherited, but prevent a method from bei.pdfCan you allow a class to be inherited, but prevent a method from bei.pdf
Can you allow a class to be inherited, but prevent a method from bei.pdf
 
Write the Java source code necessary to build a solution for EITHER .pdf
Write the Java source code necessary to build a solution for EITHER .pdfWrite the Java source code necessary to build a solution for EITHER .pdf
Write the Java source code necessary to build a solution for EITHER .pdf
 
Which type of protein does DNA wrap around so that it can be package.pdf
Which type of protein does DNA wrap around so that it can be package.pdfWhich type of protein does DNA wrap around so that it can be package.pdf
Which type of protein does DNA wrap around so that it can be package.pdf
 
Why is the death of Socrates important How did it underscore or und.pdf
Why is the death of Socrates important How did it underscore or und.pdfWhy is the death of Socrates important How did it underscore or und.pdf
Why is the death of Socrates important How did it underscore or und.pdf
 
Which of the following was Darwin unaware ofQuestion 2 options.pdf
Which of the following was Darwin unaware ofQuestion 2 options.pdfWhich of the following was Darwin unaware ofQuestion 2 options.pdf
Which of the following was Darwin unaware ofQuestion 2 options.pdf
 
When an eye appears bloodshot the vessels that are visible are in wh.pdf
When an eye appears bloodshot the vessels that are visible are in wh.pdfWhen an eye appears bloodshot the vessels that are visible are in wh.pdf
When an eye appears bloodshot the vessels that are visible are in wh.pdf
 
What is body fatSolutionBody fat is the total fat content in .pdf
What is body fatSolutionBody fat is the total fat content in .pdfWhat is body fatSolutionBody fat is the total fat content in .pdf
What is body fatSolutionBody fat is the total fat content in .pdf
 
What factors affect the degree of membrane fluidity Explain in deta.pdf
What factors affect the degree of membrane fluidity Explain in deta.pdfWhat factors affect the degree of membrane fluidity Explain in deta.pdf
What factors affect the degree of membrane fluidity Explain in deta.pdf
 
The probability thatapresident of the United States attends Harvard .pdf
The probability thatapresident of the United States attends Harvard .pdfThe probability thatapresident of the United States attends Harvard .pdf
The probability thatapresident of the United States attends Harvard .pdf
 
The pentose phosphate cycle has an oxidative and a nonoxidative sect.pdf
The pentose phosphate cycle has an oxidative and a nonoxidative sect.pdfThe pentose phosphate cycle has an oxidative and a nonoxidative sect.pdf
The pentose phosphate cycle has an oxidative and a nonoxidative sect.pdf
 
Standpoint theory suggests that our understanding of gender-based co.pdf
Standpoint theory suggests that our understanding of gender-based co.pdfStandpoint theory suggests that our understanding of gender-based co.pdf
Standpoint theory suggests that our understanding of gender-based co.pdf
 
select an engineering articlejournal with ethical senerio and justi.pdf
select an engineering articlejournal with ethical senerio and justi.pdfselect an engineering articlejournal with ethical senerio and justi.pdf
select an engineering articlejournal with ethical senerio and justi.pdf
 
Que don 20 (1 point) C D You discover a heritable trait that is found.pdf
Que don 20 (1 point) C D You discover a heritable trait that is found.pdfQue don 20 (1 point) C D You discover a heritable trait that is found.pdf
Que don 20 (1 point) C D You discover a heritable trait that is found.pdf
 
Parthenogenesis has been documented in most vertebrate Classes (e.g. .pdf
Parthenogenesis has been documented in most vertebrate Classes (e.g. .pdfParthenogenesis has been documented in most vertebrate Classes (e.g. .pdf
Parthenogenesis has been documented in most vertebrate Classes (e.g. .pdf
 
organisms in this domain first produce oxygenSolutionThe three.pdf
organisms in this domain first produce oxygenSolutionThe three.pdforganisms in this domain first produce oxygenSolutionThe three.pdf
organisms in this domain first produce oxygenSolutionThe three.pdf
 
In the cae below identify the subject matter of the controversy, whe.pdf
In the cae below identify the subject matter of the controversy, whe.pdfIn the cae below identify the subject matter of the controversy, whe.pdf
In the cae below identify the subject matter of the controversy, whe.pdf
 
Listed below are the major steps in protein synthesis and some event.pdf
Listed below are the major steps in protein synthesis and some event.pdfListed below are the major steps in protein synthesis and some event.pdf
Listed below are the major steps in protein synthesis and some event.pdf
 
1.What are 2nd messengers Give specific examples. How are they used.pdf
1.What are 2nd messengers Give specific examples. How are they used.pdf1.What are 2nd messengers Give specific examples. How are they used.pdf
1.What are 2nd messengers Give specific examples. How are they used.pdf
 
In a Pp heterozygous organisms, one of the chromosomes carrying the .pdf
In a Pp heterozygous organisms, one of the chromosomes carrying the .pdfIn a Pp heterozygous organisms, one of the chromosomes carrying the .pdf
In a Pp heterozygous organisms, one of the chromosomes carrying the .pdf
 
How do vesicles carrying proteins destined for secretion move to the .pdf
How do vesicles carrying proteins destined for secretion move to the .pdfHow do vesicles carrying proteins destined for secretion move to the .pdf
How do vesicles carrying proteins destined for secretion move to the .pdf
 

Recently uploaded

Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 

Recently uploaded (20)

Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 

(Match grouping symbols) A Java program contains various pairs of gr.pdf

  • 1. (Match grouping symbols) A Java program contains various pairs of grouping symbols, such as: Parentheses: ( and ) Braces: { and } Brackets: [ and ] Note that the grouping symbols cannot overlap. For example, (a{b)} is illegal. Write a program to check whether a Java source-code file has correct pairs of grouping symbols. Pass the source- code file name as a command-line argument. Solution // GroupingSymbols.java import java.io.*; import java.util.*; public class GroupingSymbols { public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: filename"); System.exit(0); } File inputFile = new File(args[0]); // Check if file exists if (!inputFile.exists()) { System.out.println("File does not exist!"); System.exit(1); } // Create a stack Stack charstack = new Stack<>(); // arraylist ArrayList symbolarray = new ArrayList<>(); // addinng all symbols to collection Collections.addAll(symbolarray, "(", ")", "{", "}", "[", "]"); try(BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))))
  • 2. { String str; while ((str = bf.readLine()) != null) { for (char character : str.toCharArray()) { String s = character + ""; int sIndex = symbolarray.indexOf(s); if (sIndex == -1) continue; if (charstack.size() == 0) { charstack.push(s); } else { int lIndex = symbolarray.indexOf(charstack.peek()); if (sIndex - 1 == lIndex) { charstack.pop(); } else { if ((lIndex & 1) == 1) { System.out.println("ERROR at:" + str); } charstack.push(s); } } } } } catch (FileNotFoundException exception) { System.out.println("File not found.");