Write a Java program that meets the following requirements:- Using up to and inc
ID: 3803963 • Letter: W
Question
Write a Java program that meets the following requirements:-
Using up to and including Chapter 20 concepts.
Find in the EBook at the end of the chapter, “#20.11 Match Grouping Symbols”
You might want to check out the “StringTokenizer” class to use in this program
20.11 (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.
Explanation / Answer
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
MatchingPairs.java :
__________________
public class MatchingPairs {
public static void main(String[] args) {
try{
File file = new File(args[0]);
FileInputStream fis = new FileInputStream(file);
HashMap<Character,Integer> hmp = new HashMap<Character, Integer>();
while(fis.available() > 0){
char ch =(char)fis.read();
if(ch == '(' || ch == ')'){
if(hmp.containsKey('('))
hmp.put('(',hmp.get('(')+1);
else
hmp.put('(',1);
}
else if(ch == '{' || ch == '}'){
if(hmp.containsKey('{'))
hmp.put('{',hmp.get('{')+1);
else
hmp.put('{',1);
}
else if(ch == '[' || ch == ']'){
if(hmp.containsKey('['))
hmp.put('[',hmp.get('[')+1);
else
hmp.put('[',1);
}
}
boolean flag = true;
for(char key : hmp.keySet()){
int count = hmp.get(key);
if(count%2 == 0)
continue;
else
flag = false;
}
if(flag)
System.out.println("'"+file.getName()+"' source-code file has correct pairs of grouping symbols.");
else
System.out.println("'"+file.getName()+"' source-code file not has correct pairs of grouping symbols.");
fis.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
input.txt :
________
hello kanakala lakshmna rao
{welcom(e to our}inchegg(in vizag[ what about your family]em dng{
)hello})wh[atsup] bye.
Passing File as Command Line argument:
___________________________________
java MatchingPairs F:\input.txt
Sample Output:
'input.txt' source-code file has correct pairs of grouping symbols.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.