Author: Joshua Nwokoye
This Java program is designed to transform a composition of functions, given as input, into an equivalent mathematical expression while preserving the order of operations and removing unnecessary brackets. It follows the specified grammar and operator precedence rules.
The program is made up of the following parts:
- Lexer.java
- Parser.java
- Token.java
- Main.java
The Lexer class is responsible for tokenizing the input mathematical expression. It uses regular expressions to identify different types of tokens, such as numbers, operators, whitespace, and parentheses. The tokens are then used by the Parser for further processing.
class Lexer {
public Lexer(String input) {
// Constructor takes the input expression and removes comments.
// ...
}
public Token getNextToken() {
// Method to retrieve the next token in the expression.
// ...
}
}
The Parser class takes the tokens generated by the Lexer and converts the infix mathematical expression into a postfix expression. It uses the Shunting Yard algorithm to achieve this. The parse method returns the equivalent postfix expression.
class Parser {
public Parser(Lexer lexer) {
// Constructor takes the lexer object.
// ...
}
public String parse() {
// Method to parse the input expression.
// ...
}
}
The Token class represents a token in the mathematical expression. Each token has a type (e.g., NUMBER, OPERATOR) and a corresponding value.
class Token {
public Token(TokenType type, String value) {
// Constructor takes the token type and value.
// ...
}
public TokenType getType() {
// Method to retrieve the token type.
// ...
}
public String getValue() {
// Method to retrieve the token value.
// ...
}
}
The Main class provides an example of how to use the Lexer and Parser to evaluate a mathematical expression. The example expression is defined in the Main class, and the result is printed to the console.
class Main {
public static void main(String[] args) {
// Example expression.
String input = "f(g(x))";
// Create a lexer object.
Lexer lexer = new Lexer(input);
// Create a parser object.
Parser parser = new Parser(lexer);
// Parse the expression.
String output = parser.parse();
// Print the result.
System.out.println(output);
}
}
To run the program in merlin server, follow these steps:
-
Ensure you have Java installed on your system. You can download it from Oracle or use a package manager on your platform.
-
Sign in to your merlin sever.
-
Compile the Java source files:
javac Main.java
-
To run the compiled source files:
java Main
-
To run with makefile:
make run