ProductsLogo
LogoStudy Documents
LogoAI Grader
LogoAI Answer
LogoAI Code Checker
LogoPlagiarism Checker
LogoAI Paraphraser
LogoAI Quiz
LogoAI Detector
PricingBlogAbout Us
logo

Java Programs for Infix, Postfix and Interpreter

Verified

Added on  2023/06/11

|88
|9426
|328
AI Summary
This article contains Java programs for infix, postfix and interpreter. The programs include Infix to Postfix conversion, Interpreter Demo, Postfix to Infix conversion, Euclid algorithm, IdentToken and InputData. These programs are useful for students studying computer science and related fields. The article also provides solved assignments, essays, dissertations and more related to these programs at Desklib. Students can get expert assistance and improve their grades.

Contribute Materials

Your contribution can guide someone’s learning journey. Share your documents today.
Document Page
1. Infix java Program:
import java.util.Stack;
class infix
{
//the given operator precedence returned by the function
//if it is returned means it has higher precedence
static int Precious(char choice)
{
switch (choice)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
}
//converting to infix expression in main method
// for expressing post_fix
static String infixToPost_fix(String expect)
{
// empty string initialization
String result = new String("the expression for infix is : ");
// empty stack initialization
Stack<Character> stack = new Stack<>();
for (int j = 0; j<expect.length(); ++j)
{
char ch = expect.charAt(j);
//adding to the output.
if (Character.isLetterOrDigit(ch))
result += ch;
// pushing to the stack.
else if (ch == '(')
stack.push(ch);
Document Page
//checking the condition
else if (ch == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return "the Expression is invalid"; // expression checking
else
stack.pop();
}
else //
{
while (!stack.isEmpty() && Precious(ch) <=
Precious(stack.peek()))
result += stack.pop();
stack.push(ch);
}
}
Document Page
// from the stack pope the operators
while (!stack.isEmpty())
result += stack.pop();
return result;
}
// driver method
public static void main(String[] args)
{
String exp = "(x+y-z*x)";
//String exp1= "(x+y+z%x)";
System.out.println(infixToPost_fix(exp));
//System.out.println(infixToPost_fix(exp1));
}
}
2. InterpreterDemo java program:
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class InterpreterDemo {

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
public static boolean precedence(char x, char y) {
String higher = "*/", lower = "+-";
if (x == '(') {
return false;
}
if (x == ')' && y == '(') {
System.out.println(")-(");
return false;
}
if (y == '(') {
return false;
}
if (y == ')') {
return true;
}
if (higher.indexOf(x) > - 1 && lower.indexOf(y) > - 1) {
return true;
}
if (higher.indexOf(x) > - 1 && higher.indexOf(y) > - 1) {
return true;
}
if (lower.indexOf(x) > - 1 && lower.indexOf(y) > - 1) {
return true;
Document Page
}
return false;
}
public static String convertToPostfix(String expr) {
Stack<Character> stackOperations = new Stack<>();
StringBuilder out = new StringBuilder();
String operations = "+-*/()";
char topSymbol = '+';
boolean empty;
String[] tokens = expr.split(" ");
for (String token : tokens) {
if (operations.indexOf(token.charAt(0)) == -1) {
out.append(token);
out.append(' ');
} else {
while (!(empty = stackOperations.isEmpty()) &&
precedence(topSymbol = stackOperations.pop(), token.charAt(0))) {
out.append(topSymbol);
out.append(' ');
}
if (!empty) {
stackOperations.push(topSymbol);
Document Page
}
if (empty || token.charAt(0) != ')') {
stackOperations.push(token.charAt(0));
} else {
topSymbol = stackOperations.pop();
}
}
}
while (!stackOperations.isEmpty()) {
out.append(stackOperations.pop());
out.append(' ');
}
return out.toString();
}
public static double processPostfix(String postfix, Map <String, Integer> map) {
Stack<Double> stack = new Stack<>();
String operations = "+-*/";
String[] tokens = postfix.split(" ");
for (String token : tokens) {
if (operations.indexOf(token.charAt(0)) == -1) {
double term;

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
try {
term = Double.parseDouble(token);
} catch (NumberFormatException ex) {
term = map.get(token);
}
stack.push(term);
} else {
double x = stack.pop(), y = stack.pop();
if (token.charAt(0) == '+') {
x = x + y;
}
if (token.charAt(0) == '-') {
x = x - y;
}
if (token.charAt(0) == '*') {
x = x * y;
}
if (token.charAt(0) == '/') {
x =x / y;
}
stack.push(x);
Document Page
}
}
return stack.pop();
}
public static void main(String[] args) {
String interinfix = "v * 9 / 5 + 32";
String interpostfix = convertToPostfix(interinfix);
System.out.println("Infix: " + interinfix);
System.out.println("Postfix: " + interpostfix);
Map < String, Integer > map = new HashMap<>();
for (int i = 0; i <= 100; i += 10) {
map.put("v", i);
System.out.println("v is " + i + ", G is " + processPostfix(interpostfix, map));
}
}
}
3. Post_fixToInfix java program:
import java.util.Scanner;
import java.util.Stack;
public class Post_fixToInfix
Document Page
{
private static Scanner SC;
// checking the operators
private boolean isOperator(char c){
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
return true;
return false;
}
// logic for converting infix to post-fix
public String convert(String fixpost){
Stack<String> s = new Stack<>();
for(int j = 0; j < fixpost.length(); j++){
char c = fixpost.charAt(j);
if(isOperator(c)){
String b = s.pop();
String a = s.pop();
s.push("("+a+c+b+")");

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
}
else
s.push(""+c);
}
return s.pop();
}
public static void main(String[] args) {
Post_fixToInfix obj = new Post_fixToInfix();
SC = new Scanner(System.in);
System.out.print("enter the Postfix notation : ");
String fixpost = SC.next();
System.out.println("Infix notation for entered notation is : "+obj.convert(fixpost));
}
}
4. Euclid java program:
package infix;
import java.io.IOException;
import java.util.Hashtable;
Document Page
public class Euclid {
public static final int MAX_NUM_TOKENS = 3000; // You may assume there will be no
more than 3000 tokens
public static Token[] tokenSequence = new Token[MAX_NUM_TOKENS];
public static int currentToken=0;
public static Hashtable<String, IdentToken> idents;
public static boolean lexAnalysisSuccessful = true;
public static void main(String[] args) {
System.out.println("Enter source file path:");
InputData.filePath = System.console().readLine("");
LexAnalyser lex = new LexAnalyser();
Token nextToken = new Token(TokenType.END_OF_LINE);
do {
Document Page
try {
nextToken = lex.scan();
tokenSequence[currentToken] = nextToken;
if(nextToken.returnType() == TokenType.NULL_TOKEN){
lexAnalysisSuccessful = false;
break;
}
currentToken++;
}
catch(IOException ex) {
System.out.println("Syntax Error");
}
//nextToken.print();
} while(nextToken.returnType() != TokenType.END_OF_FILE);
System.out.println("Lexical analysis successful");
// Lexical analysis complete, now on to parsing..
idents = lex.getIdentifiers();
// This next declaration passes the sequence of tokens and hastable of identifiers to the
parser

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
Parser pars = new Parser(tokenSequence, idents);
pars.prog();
System.out.println("Parsing successful.");
Interpreter interpreter = new Interpreter(tokenSequence);
interpreter.exec();
}
}
5. IdentToken java program:
package infix;
public class IdentToken extends Token {
public String identifierName;
public int value;
public IdentToken(String identName) {
super(TokenType.ID);
identifierName = identName;
value = 0;
}
public String getIdName() {
Document Page
return identifierName;
}
public void setValue(int newValue) {
value = newValue;
}
public int getValue() {
return value;
}
@Override
public int hashCode() {
return identifierName.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null){
return false;
}
if (obj instanceof IdentToken){
Document Page
IdentToken token = (IdentToken)obj;
return identifierName.equals(token.identifierName);
}
return false;
}
public void print() {
System.out.println("Identifier Token: " + identifierName);
}
}
6. Input data java program:
package infix;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class InputData {

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
private static final String REGEX = "//.*|(\"(?:\\\\[^\"]|\\\\\"|.)*?\")|(?s)/\\*.*?\\*/";
//filepath
public static String filePath = "";
//filecontent
public static String value = "";
// return filecontent.
public static String getInputString(){
value = get();
value = value.replaceAll( "(//.*?$)", "" );
while (true){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(value); // get a matcher object
if(m.find()) {
String find = m.group();
String newString = "";
for( int i=0; i<find.length(); i++ ) {
Document Page
if( find.charAt(i) == '\n' ) {
newString += "\n";
}
}
value = value.substring(0,
m.start())+newString+value.substring(m.end(),value.length());
}else{
break;
}
}
return value;
}
/**
* This method reads input source file.
* @return filecontent.
*/
public static String get(){
//create file object
File file = new File(filePath);
BufferedInputStream bin = null;
try
Document Page
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);
//create object of BufferedInputStream
bin = new BufferedInputStream(fin);
//create a byte array
byte[] contents = new byte[1024];
int bytesRead=0;
String strFileContents = "";
while( (bytesRead = bin.read(contents)) != -1){
strFileContents = new String(contents, 0, bytesRead);
}
return strFileContents;
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
catch(IOException ioe)
{
System.out.println("Exception while reading the file "
+ ioe);
}
finally
{
//close the BufferedInputStream using close method
try{
if(bin != null)
bin.close();
}catch(IOException ioe)
{
System.out.println("Error while closing the stream :"
+ ioe);
}
}
System.exit(-1);
return "";
}
}
Document Page
7. Interpreter java program:
package infix;
import java.util.Hashtable;
/**
* This is Interpreter execute source code and print output on std output stream
*/
public class Interpreter {
private Token[] tokens; // Array of tokens to be parsed
private int position; // Current position in array
private int line = 1;
Hashtable<IdentToken, Integer> symbolTable = new Hashtable<>(); //symbol table to store
values of identifiers
/**
* Constructor to initilise tokens and positions
* @param tokenSeq Tokens Collection
*/
public Interpreter(Token[] tokenSeq) {
tokens = tokenSeq;
position = 0; // Current position in sequence
Document Page
}
/**
* This method starts execution of program
*/
public void exec(){
initilizeVariables();
executeExprs();
end_of_file();
}
private void parseError() {
//System.out.println("Interpreter Error on:");
//tokens[position].print();
//System.out.println("Type:"+tokens[position].returnType());
//System.out.println("Line: "+line);
}
private boolean checkID(){
if (check(TokenType.ID)){
IdentToken id = (IdentToken)tokens[position];
if (symbolTable.containsKey(id)){

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
return true;
}else{
System.out.println("Undefine symbol:"+id.getIdName()+" at line:"+line);
System.exit(-1);
return false;
}
}else {
return false;
}
}
// The following helper method allows us to check if the current token.
// is of type tokType without incrementing the position counter.
private boolean check(TokenType tokType) {
if(tokens[position].returnType() != tokType) {
return false;
}
return true;
}
//method to initilize variables and add them to symboltable.
private void initilizeVariables() {
Document Page
position = 0;
while (true){
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken)tokens[position];
if (keywordToken.getKeyword().equals("INT")){
position++;
if (check(TokenType.ID)){
IdentToken idToken = (IdentToken)tokens[position];
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
position++;
if (!symbolTable.containsKey(idToken)){
symbolTable.put(idToken, 0);
}else{
System.out.println("Attempting to declare an already declared variable:
"+keywordToken.getKeyword()+" "+idToken.getIdName()+" at line "+line);
System.exit(-1);
}
line++;
}else{
Document Page
System.out.println("Expected Token: 'New Line' after
"+keywordToken.getKeyword()+" "+idToken.getIdName()+";"+" at line "+line);
System.exit(-1);
}
}else{
System.out.println("Expected Token: ';' after
"+keywordToken.getKeyword()+" "+idToken.getIdName()+" at line "+line);
System.exit(-1);
}
}else{
System.out.println("Expected Token: identifier after
"+keywordToken.getKeyword()+" at line "+line);
System.exit(-1);
}
}else{
break;
}
}else{
break;
//System.out.println("Expected Token: INT at line "+line);
//System.exit(-1);
}
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
}
//method to starts execution of expression after initilization of variables.
private void executeExprs() {
while (true){
if (check(TokenType.END_OF_FILE)){
return;
}
if (check(TokenType.END_OF_LINE)){
position++;
continue;
} if (check(TokenType.ID)){
hitAndExecAssignmentExp(true);
}else if (check(TokenType.KEYWORD)) {
KeywordToken keyword = (KeywordToken)tokens[position];
Document Page
if (keyword.getKeyword().equals("WHILE")){
hitAndExecWhile(true);
}else if (keyword.getKeyword().equals("IF")){
hitAndExecIfExp(true);
}else if (keyword.getKeyword().equals("OUTPUT")){
hitAndExecPrintExp(true);
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}
}
Document Page
/**
* End of file char ($).
*/
private void end_of_file() {
if (!check(TokenType.END_OF_FILE)){
parseError();
System.exit(-1);
}
}
// The rest of the methods are up to you to write
/**
* This method executes while loop expression (WHILE THEN ENDEHILE).
* @param condiction flag
* @return true only and only if success.
*/
private boolean hitAndExecWhile(boolean condiction){
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken) tokens[position];
if (keywordToken.getKeyword().equals("WHILE")){
position++;
int oldPosition = position;

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
boolean outerflag = true;
outer: while (outerflag){
position = oldPosition;
Boolean[] values = hitAndExecBooleanExp();
outerflag = condiction;
condiction = condiction && values[1];
if (values[0]) {
if (check(TokenType.KEYWORD)) {
KeywordToken then = (KeywordToken) tokens[position];
if (then.getKeyword().equals("THEN")) {
position++;
if (check(TokenType.END_OF_LINE)) {
position++;
line++;
do {
if (check(TokenType.KEYWORD)) {
KeywordToken endWhile = (KeywordToken) tokens[position];
Document Page
if (endWhile.getKeyword().equals("ENDWHILE")) {
position++;
if (check(TokenType.END_OF_LINE)) {
position++;
line++;
if (!outerflag){
return true;
}else{
continue outer;
}
//return true;
} else {
parseError();
System.exit(-1);
}
}
}
if (hitAndExecPrintExp(condiction)) {
continue;
Document Page
} else if (hitAndExecAssignmentExp(condiction)) {
continue;
} else if (hitAndExecIfExp(condiction)) {
continue;
} else if (hitAndExecWhile(condiction)) {
continue;
} else if (check(TokenType.END_OF_LINE)) {
line++;
position++;
} else {
parseError();
System.exit(-1);
}
} while (true);
} else {
parseError();
System.exit(-1);
}
} else {
parseError();

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
System.exit(-1);
}
} else {
parseError();
System.exit(-1);
}
} else {
parseError();
System.exit(-1);
}
}
}
}
return false;
}
/**
* This method executes Assignment expression (IS).
* @param condition flag
* @return true only and only if success.
*/
private boolean hitAndExecAssignmentExp(boolean condition){
Document Page
if (checkID()){
IdentToken identToken = (IdentToken)tokens[position];
position++;
if (check(TokenType.KEYWORD)){
KeywordToken keyword = (KeywordToken)tokens[position];
if (keyword.getKeyword().equals("IS")){
position++;
Object[] values = hitAndExecIntExp();
boolean flag = (boolean) values[0];
int newValue = (int) values[1];
if (flag && condition){
symbolTable.put(identToken, newValue);
}
return flag;
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
Document Page
}
}else{
return false;
//parseError();
//System.exit(-1);
}
return true;
}
/**
* This method executes IF Statement (IF THEN ENDIF).
* @param condiction flag
* @return true only and only if success.
*/
private boolean hitAndExecIfExp(boolean condiction){
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken) tokens[position];
if (keywordToken.getKeyword().equals("IF")){
position++;
Boolean[]values = hitAndExecBooleanExp();
condiction = condiction && values[1];

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
if (values[0]){
if (check(TokenType.KEYWORD)) {
KeywordToken then = (KeywordToken) tokens[position];
if (then.getKeyword().equals("THEN")) {
position++;
if (check(TokenType.END_OF_LINE)){
position++;
line++;
do{
if (check(TokenType.KEYWORD)) {
KeywordToken endif = (KeywordToken) tokens[position];
if (endif.getKeyword().equals("ENDIF")) {
position++;
if(check(TokenType.END_OF_LINE)){
line++;
position++;
return true;
}else{
parseError();
System.exit(-1);
}
Document Page
}
}
if(hitAndExecPrintExp(condiction)){
continue;
}else if (hitAndExecAssignmentExp(condiction)){
continue;
}else if (hitAndExecIfExp(condiction)){
continue;
}else if (hitAndExecWhile(condiction)){
continue;
}else if (check(TokenType.END_OF_LINE)){
line++;
position++;
}else{
parseError();
System.exit(-1);
}
}while (true);
}else{
parseError();
System.exit(-1);
Document Page
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}
}
return false;
}
/**
* This method executes print statement (OUTPUT).
* @param condition flag

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
* @return true only and only if success.
*/
private boolean hitAndExecPrintExp(boolean condition){
if (check(TokenType.KEYWORD)){
KeywordToken keyword = (KeywordToken)tokens[position];
if (keyword.getKeyword().equals("OUTPUT")){
position++;
if (check(TokenType.LBRACKET)){
position++;
if (check(TokenType.NUM) || check(TokenType.ID)){
int printValue = 0;
if (check(TokenType.NUM)){
printValue = ((NumToken)tokens[position]).intValue;
}else {
IdentToken identToken = (IdentToken)tokens[position];
printValue = symbolTable.get(identToken);
}
position++;
if (check(TokenType.RBRACKET)){
position++;
Document Page
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
if (condition)
System.out.println(printValue);
return true;
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
Document Page
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
return false;
//parseError();
//System.exit(-1);
}
}else{
return false;
//parseError();
//System.exit(-1);
}
return true;
}
/**
* This method execute boolean condition either Boolean literal or Expression.
* @return Array of success hit(bool) and condition result(bool).

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
*/
private Boolean[] hitAndExecBooleanExp(){
Boolean[] values = isBoolLiteralCond();
if (values[0]){
return values;
}
if (check(TokenType.LBRACKET)){
position++;
if (check(TokenType.NUM) || check(TokenType.ID)){ //first operand
int firstOperand = 0;
if (check(TokenType.NUM)){
firstOperand = ((NumToken)tokens[position]).intValue;
}else {
IdentToken identToken = (IdentToken)tokens[position];
firstOperand = symbolTable.get(identToken);
}
position++;
Document Page
if (check(TokenType.OPERATOR)){ // operator if exists
OperatorToken op = (OperatorToken)tokens[position];
if (op.isBoolOperator()){
position++;
if (check(TokenType.NUM) || check(TokenType.ID)) { //second operand
int secondOperand = 0;
if (check(TokenType.NUM)){
secondOperand = ((NumToken)tokens[position]).intValue;
}else {
IdentToken identToken = (IdentToken)tokens[position];
secondOperand = symbolTable.get(identToken);
}
values[1] = op.applyConditionalOperator(firstOperand, secondOperand);
position++;
if (check(TokenType.RBRACKET)){
position++;
values[0] = true;
return values;
}else{
Document Page
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else {
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
values[0] = false;
values[1] = false;
return values;
}
/**
* This method execute Int expression either Int literal or Expression.
* @return Array of success hit(bool) and condition result(Int).
*/
private Object[] hitAndExecIntExp(){
Object[] values = isIntLiteral();
Boolean flag = (Boolean)values[0];
if (flag){
return values;
}
if (check(TokenType.NUM) || checkID()){ //first operand
int firstOperand = 0;
if (check(TokenType.NUM)){
Document Page
firstOperand = ((NumToken)tokens[position]).intValue;
}else {
IdentToken identToken = (IdentToken)tokens[position];
firstOperand = symbolTable.get(identToken);
}
position++;
if (check(TokenType.OPERATOR)){ // operator if exists
OperatorToken op = (OperatorToken)tokens[position];
if (op.isIntOperator()){
position++;
if (check(TokenType.NUM) || checkID()) { //second operand
int secondOperand = 0;
if (check(TokenType.NUM)){
secondOperand = ((NumToken)tokens[position]).intValue;
}else {
IdentToken identToken = (IdentToken)tokens[position];
secondOperand = symbolTable.get(identToken);
}
Document Page
values[1] = op.applyIntOperator(firstOperand, secondOperand);
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
values[0] = true;
return values;
}else {
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
values[1] = firstOperand;
return values;
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else {
parseError();
Document Page
System.exit(-1);
}
values[0] = false;
values[1] = -1;
return values;
}
/**
* This method execute boolean condition Boolean literal only.
* @return Array of success hit(bool) and condition result(bool).
*/
private Boolean[] isBoolLiteralCond(){
if (check(TokenType.LBRACKET)){
position++;
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken)tokens[position];
if (keywordToken.getKeyword().equals("TRUE") ||
keywordToken.getKeyword().equals("FALSE")){
position++;
if (check(TokenType.RBRACKET)){
Document Page
position++;
return new Boolean[]{true, keywordToken.getKeyword().equals("TRUE")};
}else{
parseError();
System.exit(-1);
}
}else{
//nothing
}
}else{
position--;
}
}
return new Boolean[]{false, false};
}
/**
* This method execute Int expression Int literal only.
* @return Array of success hit(bool) and condition result(Int).
*/
private Object[] isIntLiteral(){

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
if (check(TokenType.NUM)){
NumToken numToken = (NumToken)tokens[position];
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
return new Object[]{true, numToken.intValue};
}else{
parseError();
System.exit(-1);
}
}else{
position--;
}
}
return new Object[]{false, 0};
}
}
8. Keyword java program:
package infix;
Document Page
public class KeywordToken extends Token {
public String keyword;
public KeywordToken(String keywordVal) {
super(TokenType.KEYWORD);
keyword = keywordVal;
}
public String getKeyword() {
return keyword;
}
public void print() {
System.out.println("Keyword Token: " + keyword);
}
}
9. Lex analyzer:
package infix;
import java.io.IOException;
import java.util.Hashtable;
import java.util.StringTokenizer;
Document Page
public class LexAnalyser {
public int lineNumber = 1;
private Hashtable<String, IdentToken> identifiers = new Hashtable<>();
private Hashtable<String, KeywordToken> reservedKeywords = new Hashtable<>();
private StringTokenizer tokenizer = null;
void addIdentifier(IdentToken t) { identifiers.put(t.identifierName, t); }
public LexAnalyser() {
// When a LexAnalyser object is created, populate the reservedKeywords hashtable with all
keywords
reservedKeywords.put("WHILE", new KeywordToken("WHILE"));
reservedKeywords.put("IF", new KeywordToken("IF"));
reservedKeywords.put("THEN", new KeywordToken("THEN"));
reservedKeywords.put("ENDIF", new KeywordToken("ENDIF"));
reservedKeywords.put("ENDWHILE", new KeywordToken("ENDWHILE"));
reservedKeywords.put("INT", new KeywordToken("INT"));
reservedKeywords.put("PRINT", new KeywordToken("PRINT"));
reservedKeywords.put("IS", new KeywordToken("IS"));
reservedKeywords.put("OUTPUT", new KeywordToken("OUTPUT"));

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
reservedKeywords.put("TRUE", new KeywordToken("TRUE"));
reservedKeywords.put("FALSE", new KeywordToken("FALSE"));
tokenizer = new StringTokenizer(InputData.getInputString(), " ;()\t\r\n\f{}+-%<>!", true);
}
// This next method is for you to write, to scan the input and return the correct Token for the
next lexeme
// The comments inside the scan() method may help you to structure your code
public Token scan() throws IOException
{
// First we may read characters until end of whitespace (spaces, tabs or newlines)...
if (tokenizer.hasMoreTokens()){
String token = tokenizer.nextToken();
if (token.equals("$")){
return new Token(TokenType.END_OF_FILE);
}else if (reservedKeywords.containsKey(token.trim())) {
return reservedKeywords.get(token);
}else if (token.equals("(")){
return new Token(TokenType.LBRACKET);
}else if (token.equals(")")) {
Document Page
return new Token(TokenType.RBRACKET);
}else if (token.equals(";")){
return new Token(TokenType.TERMINATOR);
}else if (token.equals(" ") || token.equals("\t") || token.equals("\r") || token.equals("\f")) {
return scan();
}else if (token.equals("\n")){
lineNumber++;
return new Token(TokenType.END_OF_LINE);
}else if (token.equals("+")){
return new OperatorToken(OperatorType.PLUS);
}else if (token.equals("–")){
return new OperatorToken(OperatorType.MINUS);
}else if (token.equals("%")){
return new OperatorToken(OperatorType.MODULUS);
}else if (token.equals("!")) {
return new OperatorToken(OperatorType.NOT_EQUAL);
}else if (token.equals("*")){
return new OperatorToken(OperatorType.MULTIPLY);
}else if (token.equals("<")){
return new OperatorToken(OperatorType.LESS_THAN);
}else if (token.equals(">")){
return new OperatorToken(OperatorType.GREATER_THAN);
}
Document Page
try{
int value = Integer.parseInt(token);
return new NumToken(value);
}catch(NumberFormatException ex){ }
try{
Double.parseDouble(token);
System.out.println("Error in lexical analysis of program at line:"+lineNumber+ "
(invalid int literal:"+token+")");
System.exit(-1);
return new Token(TokenType.NULL_TOKEN);
}catch (NumberFormatException ex){}
char[] array = token.toCharArray();
for (char value: array) {
if (!(value >= 97 && value <= 122)){
System.out.println("Error in lexical analysis of program at line:"+lineNumber+"
(invalid identifier:"+token+")");
System.exit(-1);
return new Token(TokenType.NULL_TOKEN);
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
}
IdentToken id = new IdentToken(token);
addIdentifier(id);
return id;
}
// Now determine what type of token we have and return the correct type...
//If we have gotten to here, we have not matched any token so print an error message and
return a NULL_TOKEN
System.out.println("Syntax Error");
return new Token(TokenType.NULL_TOKEN);
}
public Hashtable<String, IdentToken> getIdentifiers() {
return identifiers;
}
}
10. Num token:
package infix;
public class NumToken extends Token {
public int intValue;
Document Page
public NumToken(int value) {
super(TokenType.NUM);
intValue = value;
}
public int getValue() {
return intValue;
}
public void print() {
System.out.println("Number Token: " + intValue);
}
}
11. Operator Token:
package infix;
public class OperatorToken extends Token {
public OperatorType opType;
public OperatorToken(OperatorType thisOp) {
super(TokenType.OPERATOR);
opType = thisOp;
Document Page
}
public OperatorType getType() {
return opType;
}
public boolean isIntOperator(){
if (opType == OperatorType.PLUS ||
opType == OperatorType.MINUS ||
opType == OperatorType.MULTIPLY ||
opType == OperatorType.MODULUS){
return true;
}else {
return false;
}
}
public boolean isBoolOperator(){
return !isIntOperator();
}
public void print() {
switch(opType) {

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
case PLUS: System.out.println("Operator Token: PLUS"); break;
case MINUS: System.out.println("Operator Token: MINUS"); break;
case MULTIPLY: System.out.println("Operator Token: MULTIPLY"); break;
case MODULUS: System.out.println("Operator Token: MODULUS"); break;
case GREATER_THAN: System.out.println("Operator Token: GREATER_THAN");
break;
case LESS_THAN: System.out.println("Operator Token: LESS_THAN"); break;
case NOT_EQUAL: System.out.println("Operator Token: NOT_EQUAL"); break;
}
}
//return int value after applying operator on operands.
public int applyIntOperator(int first, int second){
switch(opType) {
case PLUS: return first + second;
case MINUS: return first - second;
case MULTIPLY: return first * second;
case MODULUS: return first % second;
default: return 0;
}
}
Document Page
//return bool value after applying operator on operands.
public boolean applyConditionalOperator(int first, int second){
switch(opType) {
case GREATER_THAN: return first > second;
case LESS_THAN: return first < second;
case NOT_EQUAL: return first != second;
default: return false;
}
}
}
12. Operator Type:
package infix;
public enum OperatorType {
PLUS, MINUS, MULTIPLY, MODULUS, GREATER_THAN, LESS_THAN,
NOT_EQUAL
}
13. Parser java program:
package infix;
import java.util.Hashtable;
/**
Document Page
* Parser class for this application.
* This class parse source after Lexical Analyser.
*/
public class Parser {
private Token[] tokens; // Array of tokens to be parsed
private int position; // Current position in array
private int line = 1;
Hashtable<String, IdentToken> vars; // Hashtable of all identifiers
Hashtable<String, Integer> sysbolTable = new Hashtable<>(); //symbol table to store values
of identifiers
public Parser(Token[] tokenSeq, Hashtable<String, IdentToken> variables) {
tokens = tokenSeq;
position = 0; // Current position in sequence
vars = variables;
}
/**
* Print parser error to std output stream.
*/
private void parseError() {
System.out.println("Parse Error on:");
tokens[position].print();

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
System.out.println("Type:"+tokens[position].returnType());
System.out.println("Line: "+line);
}
/**
* check if token if identifier token and its is valid.
* @return true if success.
*/
private boolean checkID(){
if (check(TokenType.ID)){
IdentToken id = (IdentToken)tokens[position];
if (sysbolTable.containsKey(id.getIdName())){
return true;
}else{
System.out.println("Undefine symbol:"+id.getIdName()+" at line:"+line);
System.exit(-1);
return false;
}
}else {
return false;
}
}
Document Page
// The following helper method allows us to check if the current token
// is of type tokType without incrementing the position counter
private boolean check(TokenType tokType) {
if(tokens[position].returnType() != tokType) {
return false;
}
return true;
}
// Start to parse the program
public void prog() {
// First parse declarations
decls();
// Next parse expressions
exprs();
// Finally parse the end of file character
end_of_file();
}
/**
* Parse veribles
*/
private void decls() {
Document Page
position = 0;
while (true){
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken)tokens[position];
if (keywordToken.getKeyword().equals("INT")){
position++;
if (check(TokenType.ID)){
IdentToken idToken = (IdentToken)tokens[position];
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
position++;
if (!sysbolTable.containsKey(idToken.getIdName())){
sysbolTable.put(idToken.getIdName(), 0);
}else{
System.out.println("Attempting to declare an already declared variable:
"+keywordToken.getKeyword()+" "+idToken.getIdName()+" at line "+line);
System.exit(-1);
}
line++;
}else{

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
System.out.println("Expected Token: 'New Line' after
"+keywordToken.getKeyword()+" "+idToken.getIdName()+";"+" at line "+line);
System.exit(-1);
}
}else{
System.out.println("Expected Token: ';' after
"+keywordToken.getKeyword()+" "+idToken.getIdName()+" at line "+line);
System.exit(-1);
}
}else{
System.out.println("Expected Token: identifier after
"+keywordToken.getKeyword()+" at line "+line);
System.exit(-1);
}
}else{
break;
}
}else{
break;
//System.out.println("Expected Token: INT at line "+line);
//System.exit(-1);
}
}
Document Page
}
/**
* Parse Expression
* IS
* WHILE THEN ENDWHILE
* IF THEN ENDIF
*/
private void exprs() {
while (true){
if (check(TokenType.END_OF_FILE)){
return;
}if (check(TokenType.END_OF_LINE)){
position++;
continue;
}else if (check(TokenType.ID)){
parseAssigmentExp();
}else if (check(TokenType.KEYWORD)) {
Document Page
KeywordToken keyword = (KeywordToken)tokens[position];
if (keyword.getKeyword().equals("WHILE")){
parseWhileExp();
}else if (keyword.getKeyword().equals("IF")){
parseIfExp();
}else if (keyword.getKeyword().equals("OUTPUT")){
parsePrintExp();
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
}
/**
* Parse end of file
*/
private void end_of_file() {
if (!check(TokenType.END_OF_FILE)){
parseError();
System.exit(-1);
}
}
// The rest of the methods are up to you to write
/**
* Parse while loop expression.
* @return true if success.
*/
private boolean parseWhileExp(){
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken) tokens[position];
if (keywordToken.getKeyword().equals("WHILE")){
position++;
Document Page
if (parseBooleanExp()){
if (check(TokenType.KEYWORD)) {
KeywordToken then = (KeywordToken) tokens[position];
if (then.getKeyword().equals("THEN")) {
position++;
if (check(TokenType.END_OF_LINE)){
position++;
line++;
do{
if (check(TokenType.KEYWORD)) {
KeywordToken endWhile = (KeywordToken) tokens[position];
if (endWhile.getKeyword().equals("ENDWHILE")) {
position++;
if (check(TokenType.END_OF_LINE)){
position++;
line++;
return true;
}else{
System.out.println("Excepted Token: ENDWHILE at line:"+line);
System.exit(-1);
}
Document Page
}
}
if (parsePrintExp()){
continue;
}else if (parseAssigmentExp()){
continue;
}else if (parseIfExp()){
continue;
}else if (parseWhileExp()){
continue;
}else if (check(TokenType.END_OF_LINE)){
line++;
position++;
}else{
parseError();
System.exit(-1);
}
}while (true);
}else{
parseError();
System.exit(-1);

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}
}
return false;
}
/**
* Parse assignment expression.
* @return true if success.
Document Page
*/
private boolean parseAssigmentExp(){
if (checkID()){
position++;
if (check(TokenType.KEYWORD)){
KeywordToken keyword = (KeywordToken)tokens[position];
if (keyword.getKeyword().equals("IS")){
position++;
if (parseIntExp()){
return true;
}else{
return false;
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
Document Page
return false;
//parseError();
//System.exit(-1);
}
return true;
}
/**
* Parse if expression.
* @return true if success.
*/
private boolean parseIfExp(){
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken) tokens[position];
if (keywordToken.getKeyword().equals("IF")){
position++;
if (parseBooleanExp()){
if (check(TokenType.KEYWORD)) {
KeywordToken then = (KeywordToken) tokens[position];
if (then.getKeyword().equals("THEN")) {
position++;

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
if (check(TokenType.END_OF_LINE)){
position++;
line++;
do{
if (check(TokenType.KEYWORD)) {
KeywordToken endif = (KeywordToken) tokens[position];
if (endif.getKeyword().equals("ENDIF")) {
position++;
if(check(TokenType.END_OF_LINE)){
line++;
position++;
return true;
}else{
parseError();
System.exit(-1);
}
}
}
if(parsePrintExp()){
continue;
}else if (parseAssigmentExp()){
continue;
Document Page
}else if (parseIfExp()){
continue;
}else if (parseWhileExp()){
continue;
}else if (check(TokenType.END_OF_LINE)){
line++;
position++;
}else{
System.out.println("Excepted Token: ENDIF at line:"+line);
System.exit(-1);
}
}while (true);
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
Document Page
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}
}
return false;
}
/**
* Parse Print statement
* @return true if sucess.
*/
private boolean parsePrintExp(){
if (check(TokenType.KEYWORD)){
KeywordToken keyword = (KeywordToken)tokens[position];
if (keyword.getKeyword().equals("OUTPUT")){
position++;

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
if (check(TokenType.LBRACKET)){
position++;
if (check(TokenType.NUM) || check(TokenType.ID)){
position++;
if (check(TokenType.RBRACKET)){
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
return true;
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
Document Page
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
return false;
//parseError();
//System.exit(-1);
}
}else{
return false;
//parseError();
//System.exit(-1);
}
return true;
Document Page
}
/**
* Parse boolean expression either literal or expression.
* @return true if success.
*/
private boolean parseBooleanExp(){
if (isBoolLiteralCond()){
return true;
}
if (check(TokenType.LBRACKET)){
position++;
if (check(TokenType.NUM) || check(TokenType.ID)){ //first operand
position++;
if (check(TokenType.OPERATOR)){ // operator if exists
OperatorToken op = (OperatorToken)tokens[position];
if (op.isBoolOperator()){
position++;

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
if (check(TokenType.NUM) || check(TokenType.ID)) { //second operator
position++;
if (check(TokenType.RBRACKET)){
position++;
return true;
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
Document Page
}
}else {
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
return true;
}
/**
* Parse int expression either literal or expression.
* @return true if success.
*/
private boolean parseIntExp(){
if (isIntLiteral()){
return true;
}
Document Page
if (check(TokenType.NUM) || checkID()){ //first operand
position++;
if (check(TokenType.OPERATOR)){ // operator if exists
OperatorToken op = (OperatorToken)tokens[position];
if (op.isIntOperator()){
position++;
if (check(TokenType.NUM) || checkID()) { //second operand
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
return true;
}else {
parseError();
System.exit(-1);
}
}else{

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else{
parseError();
System.exit(-1);
}
}else if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
return true;
}else{
parseError();
System.exit(-1);
}
}else{
Document Page
parseError();
System.exit(-1);
}
}else {
parseError();
System.exit(-1);
}
return true;
}
/**
* Parse boolean expression literal.
* @return true if success.
*/
private boolean isBoolLiteralCond(){
if (check(TokenType.LBRACKET)){
position++;
if (check(TokenType.KEYWORD)){
KeywordToken keywordToken = (KeywordToken)tokens[position];
if (keywordToken.getKeyword().equals("TRUE") ||
keywordToken.getKeyword().equals("FALSE")){
Document Page
position++;
if (check(TokenType.RBRACKET)){
position++;
return true;
}else{
parseError();
System.exit(-1);
}
}else{
//nothing
}
}else{
position--;
}
}
return false;
}
/**
* Parse int expression literal.
* @return true if success.

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
*/
private boolean isIntLiteral(){
if (check(TokenType.NUM)){
position++;
if (check(TokenType.TERMINATOR)){
position++;
if (check(TokenType.END_OF_LINE)){
line++;
position++;
return true;
}else{
parseError();
System.exit(-1);
}
}else{
position--;
}
}
return false;
}
}
Document Page
14. package infix;
public class Token {
TokenType thisToken;
public Token() {
thisToken = TokenType.NULL_TOKEN;
}
public Token(TokenType inputToken) {
thisToken = inputToken;
}
public TokenType returnType() {
return thisToken;
}
public void print() {
switch(thisToken) {
case OPERATOR: System.out.println("Operator Token");
case END_OF_FILE: System.out.println("END_OF_FILE Token");
case END_OF_LINE: System.out.println("END_OF_LINE Token");
default:
Document Page
break;
}
}
}
15. Token Type:
package infix;
public enum TokenType {
NUM, ID, OPERATOR, KEYWORD, END_OF_FILE, END_OF_LINE, LBRACKET,
RBRACKET, NULL_TOKEN, TERMINATOR
}
1 out of 88
[object Object]

Your All-in-One AI-Powered Toolkit for Academic Success.

Available 24*7 on WhatsApp / Email

[object Object]