Answer:
See explaination for program code
Explanation:
package com.company;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Stack;
/*
* A program which reads input from given text filename and prints
* whether it passed the pre-processing stage or not
* Sample input
* int A = (a + b);static void display(int x)
* {
* //A sample input file
* }
* */
public class MyPreprocessor {
/*
* Reads input from filename and returns a string
* containing whole text
* */
public String readInput(String filename) {
String content = "";
try {
content = new String(Files.readAllBytes(Paths.get(filename)));
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
/**
* Filters input since we are only concerned with
* a subset of input = '{}[]()/*'
*/
public String filterText(String text) {
String output = "";
for(int i = 0;i<text.length();++i) {
switch (text.charAt(i)) {
case '[':
case ']':
case '{':
case '}':
case '(':
case ')':
case '*':
case '/':
output += text.charAt(i);
}
}
return output;
}
/*
* Uses stack to determine if input is valid or not
* */
public boolean parse(String input) {
Stack<Character> St = new Stack<Character>();
// '$' is special symbol to represent bottom of stack
St.push('$');
for(int i = 0;i<input.length();++i) {
Character symbol = input.charAt(i);
if(St.peek().equals(getOpenSymbol(symbol)))
St.pop();
else St.push(symbol);
}
return St.peek() == '$';
}
private static Character getOpenSymbol(Character symbol) {
switch (symbol) {
case '}': return '{';
case ']': return '[';
case ')': return '(';
case '*': return '*';
case '/': return '/';
default: return ' ';
}
}
public static void main(String[] args) {
MyPreprocessor preprocessor = new MyPreprocessor();
String inputText = preprocessor.readInput("src/input.txt");
String filteredInput = preprocessor.filterText(inputText);
if(preprocessor.parse(filteredInput))
System.out.println("preprocessing passed.");
else System.out.println("preprocessing failed!");
}
}