9.9k views
2 votes
In most programming languages, the compiler carries a preprocessing step to determine if certain statements will compile. For instance it may check to see if parentheses match.Write a Java program that simulates the actions of a preprocessor, to detect if certain Java constructs are syntactically correct. Table 1 shows the types of Java statement formats under consideration, and also example of each statement.

User SymKat
by
3.3k points

1 Answer

4 votes

Answer:

See explaination for program code

Step-by-step 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!");

}

}

User Lars Behnke
by
3.2k points