SlideShare a Scribd company logo
1 of 8
Download to read offline
Java Programming: Below are the lexer.java, token.java, and shank.java. Shank.java is the main
method file. The goal is to make sure to read the shank.txt file as a series of tokens & show the
screenshot of shank.txt printed in console of eclipse. Make sure the lexer has all the state
machines. Attached is rubric where all the required components a lexer must have. Attached is
images of the errors the lexer has so make sure to fix those errors as well. Attached is image of
how the output must be printed out as after all the errors are fixed.
Lexer.java
package mypack;
import java.util.ArrayList;
import java.util.List;
import mypack.Token.TokenType;
import java .util.HashMap;
public class Lexer {
private static final int INTEGER_STATE = 1;
private static final int DECIMAL_STATE = 2;
private static final int IDENTIFIER_STATE = 3;
private static final int ERROR_STATE = 4;
private static final int SYMBOL_STATE = 5;
private static final int STRING_STATE = 6;
private static final int CHAR_STATE = 7;
private static final int COMMENT_STATE = 8;
private static final char EOF = (char) -1;
private static String input;
private static int index;
private static char currentChar;
private static int lineNumber = 1;
private static int indentLevel = 0;
private static int lastIndentLevel = 0;
private static HashMap<String, TokenType> keywords = new HashMap<String, TokenType>() {{
put("while", TokenType.WHILE);
put("if", TokenType.IF);
put("else", TokenType.ELSE);
put("print", TokenType.PRINT);
}};
private static HashMap<Character, TokenType> symbols = new HashMap<Character,
TokenType>() {{
put('+', TokenType.PLUS);
put('-', TokenType.MINUS);
put('*', TokenType.MULTIPLY);
put('/', TokenType.DIVIDE);
put('=', TokenType.EQUALS);
put(':', TokenType.COLON);
put(';', TokenType.SEMICOLON);
put('(', TokenType.LEFT_PAREN);
put(')', TokenType.RIGHT_PAREN);
put('{', TokenType.LEFT_BRACE);
put('}', TokenType.RIGHT_BRACE);
put('<', TokenType.LESS_THAN);
put('>', TokenType.GREATER_THAN);
}};
public Lexer(String input) {
Lexer.input = input;
index = 0;
currentChar = input.charAt(index);
}
private void nextChar() {
index++;
if (index >= input.length()) {
currentChar = EOF;
} else {
currentChar = input.charAt(index);
}
}
private void skipWhiteSpace() {
while (Character.isWhitespace(currentChar)) {
nextChar();
}
}
private int getIndentLevel() {
int level = 0;
int i = index;
char c = input.charAt(i);
while (c == ' ' || c == 't') {
if (c == 't') {
level += 1;
} else if (c == ' ') {
level += 1;
}
i++;
if (i >= input.length()) {
break;
}
c = input.charAt(i);
}
return level;
}
public List<Token> lex(String inputString) throws Exception {
input = inputString;
index = 0;
currentChar = input.charAt(index);
List<Token> tokens = new ArrayList<Token>();
while (currentChar != EOF) {
switch (currentState()) {
case INTEGER_STATE:
integerState(tokens);
break;
case DECIMAL_STATE:
decimalState(tokens);
break;
case IDENTIFIER_STATE:
identifierState(tokens);
break;
case ERROR_STATE:
errorState(tokens);
break;
case SYMBOL_STATE:
symbolState(tokens);
break;
case STRING_STATE:
stringState(tokens);
break;
case CHAR_STATE:
charState(tokens);
break;
case COMMENT_STATE:
commentState(tokens);
break;
default:
break;
}
}
return tokens;
}
private void s (List<Token> tokens) {
//TODO Auto-generated method stub
}
private static int currentState() {
if (Character.isDigit(currentChar)) {
return INTEGER_STATE;
} else if (Character.isLetter(currentChar)) {
return IDENTIFIER_STATE;
} else if (currentChar == '.') {
return DECIMAL_STATE;
} else if (Character.isLetter(currentChar)) {
return STRING_STATE;
} else if (Character.isLetter(currentChar)) {
return CHAR_STATE;
}else if (Character.isLetter(currentChar)) {
return COMMENT_STATE;
}else if (Character.isDigit(currentChar)) {
return SYMBOL_STATE;
} else {
return ERROR_STATE;
}
}
private static void integerState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.NUMBER, builder.toString()));
}
private static void decimalState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
builder.append(currentChar);
advance();
while (Character.isDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.NUMBER, builder.toString()));
}
private static void identifierState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isLetterOrDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.WORD, builder.toString()));
}
private static void errorState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isLetterOrDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.WORD, builder.toString()));
}
private static void symbolState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isLetterOrDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.SYMBOL, builder.toString()));
}
private static void stringState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isLetterOrDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.WORD, builder.toString()));
}
private static void charState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isLetterOrDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.WORD, builder.toString()));
}
private static void commentState(List<Token> tokens) {
StringBuilder builder = new StringBuilder();
while (Character.isLetterOrDigit(currentChar)) {
builder.append(currentChar);
advance();
}
tokens.add(new Token(Token.TokenType.WORD, builder.toString()));
}
private static void advance() {
index++;
if (index >= input.length()) {
currentChar = EOF;
} else {
currentChar = input.charAt(index);
}
}
}
Token.java
package mypack;
public class Token {
public enum TokenType {
WORD, WHILE, IF, ELSE,
NUMBER,
SYMBOL, PLUS, MINUS, MULTIPLY, DIVIDE, EQUALS, COLON, SEMICOLON, LEFT_PAREN,
RIGHT_PAREN, LEFT_BRACE, RIGHT_BRACE, LESS_THAN, GREATER_THAN, PRINT
}
public TokenType tokenType;
private String value;
public Token(TokenType type, String val) {
this.tokenType = type;
this.value = val;
}
public TokenType getTokenType() {
return this.tokenType;
}
public String toString() {
return this.tokenType + ": " + this.value;
}
}
Shank.java
package mypack;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Shank {
public static void main(String[] args) {
Path filePath = Paths.get("shank.txt");
Charset charset = StandardCharsets.UTF_8;
if (args.length != 1) {
System.out.println("Error: Exactly one argument is required.");
System.exit(0);
}
String filename = args[0];
try {
List<String> lines = Files.readAllLines(Paths.get(filename));
for (String line : lines) {
try {
Lexer lexer = new Lexer(line);
List<Token> tokens = lexer.lex(line);
for (Token token : tokens) {
System.out.println(token);
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
} catch (IOException e) {
System.out.println("Error: Could not read file '" + filename + "'.");
}
}
}
shank.txt
Fibonoacci (Iterative)
define add (num1,num2:integer var sum : integer)
variable counter : integer
Finonacci(N)
int N = 10;
while counter < N
define start ()
variables num1,num2,num3 : integer
add num1,num2,var num3
{num1 and num2 are added together to get num3}
num1 = num2;
num2 = num3;
counter = counter + 1;
GCD (Recursive)
define add (int a,int b : gcd)
if b = 0
sum = a
sum gcd(b, a % b)
GCD (Iterative)
define add (inta, intb : gcd)
if a = 0
sum = b
if b = 0
sum = a
while counter a != b
if a > b
a = a - b;
else
b = b - a;
sum = a;
variables a,b : integer
a = 60
b = 96
subtract a,b
input. addnum1num2varnum3num1andnum2nreaddedtogethertogetnum3num1=num2num2=
num3counter=counter+1GCDRecurgivedefineaddidentifieridentifieridentifieridentifieridentifier
identifieridentifieridentifieridentifieridentifieridentifieridentifieridentifieridentifieridentifieroperator
identifieridentifieroperatoridentifieridentifieroperatoridentifieroperatorintegerliternlidentifieridentifier
keywordidentifierCompilation failed due to following error(s).

More Related Content

Similar to Java Programming Below are the lexerjava tokenjava and .pdf

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Anna Shymchenko
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
sudhirchourasia86
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
parag978978
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
Devnology
 
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdfC++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
rahulfancycorner21
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
priestmanmable
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
adityaraj7711
 

Similar to Java Programming Below are the lexerjava tokenjava and .pdf (19)

SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
  package Chapter_20;import ToolKit.PostfixNotation;import javaf.pdf
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
string tokenization
string tokenizationstring tokenization
string tokenization
 
Droidcon Poland - From Kotlin to Machine Code
Droidcon Poland - From Kotlin to Machine CodeDroidcon Poland - From Kotlin to Machine Code
Droidcon Poland - From Kotlin to Machine Code
 
Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdfC++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 

More from adinathassociates

JAVA Please help me on this method The requirement of the m.pdf
JAVA Please help me on this method The requirement of the m.pdfJAVA Please help me on this method The requirement of the m.pdf
JAVA Please help me on this method The requirement of the m.pdf
adinathassociates
 

More from adinathassociates (20)

It is somewhat curious that this documentation does not wind.pdf
It is somewhat curious that this documentation does not wind.pdfIt is somewhat curious that this documentation does not wind.pdf
It is somewhat curious that this documentation does not wind.pdf
 
izgi ynteminin ve nceden alanm plakann sonularna gre k.pdf
izgi ynteminin ve nceden alanm plakann sonularna gre k.pdfizgi ynteminin ve nceden alanm plakann sonularna gre k.pdf
izgi ynteminin ve nceden alanm plakann sonularna gre k.pdf
 
Jamie needs a new roof on her house The cash cost is 4100.pdf
Jamie needs a new roof on her house The cash cost is 4100.pdfJamie needs a new roof on her house The cash cost is 4100.pdf
Jamie needs a new roof on her house The cash cost is 4100.pdf
 
It is necessary for Marketers to know how the customers feel.pdf
It is necessary for Marketers to know how the customers feel.pdfIt is necessary for Marketers to know how the customers feel.pdf
It is necessary for Marketers to know how the customers feel.pdf
 
James tiene la enfermedad celaca Cul de los siguientes a.pdf
James tiene la enfermedad celaca Cul de los siguientes a.pdfJames tiene la enfermedad celaca Cul de los siguientes a.pdf
James tiene la enfermedad celaca Cul de los siguientes a.pdf
 
It is difficult to quantify a value for certain biological a.pdf
It is difficult to quantify a value for certain biological a.pdfIt is difficult to quantify a value for certain biological a.pdf
It is difficult to quantify a value for certain biological a.pdf
 
It was leaked that Bergdorf Goodman treated Kayla a Hispanic.pdf
It was leaked that Bergdorf Goodman treated Kayla a Hispanic.pdfIt was leaked that Bergdorf Goodman treated Kayla a Hispanic.pdf
It was leaked that Bergdorf Goodman treated Kayla a Hispanic.pdf
 
It is possible to create dynamic GUI applications based on c.pdf
It is possible to create dynamic GUI applications based on c.pdfIt is possible to create dynamic GUI applications based on c.pdf
It is possible to create dynamic GUI applications based on c.pdf
 
Joe makes annual income of 5000 for five years Joe withdr.pdf
Joe makes annual income of 5000 for five years Joe withdr.pdfJoe makes annual income of 5000 for five years Joe withdr.pdf
Joe makes annual income of 5000 for five years Joe withdr.pdf
 
Joan Robinson ktisat okumann amac iktisat sorularna bir d.pdf
Joan Robinson ktisat okumann amac iktisat sorularna bir d.pdfJoan Robinson ktisat okumann amac iktisat sorularna bir d.pdf
Joan Robinson ktisat okumann amac iktisat sorularna bir d.pdf
 
Jobyde ie alma ilerleme terfi ve tevik etme grevleri gen.pdf
Jobyde ie alma ilerleme terfi ve tevik etme grevleri gen.pdfJobyde ie alma ilerleme terfi ve tevik etme grevleri gen.pdf
Jobyde ie alma ilerleme terfi ve tevik etme grevleri gen.pdf
 
It is not option 3 please help What would be the outcome of.pdf
It is not option 3 please help What would be the outcome of.pdfIt is not option 3 please help What would be the outcome of.pdf
It is not option 3 please help What would be the outcome of.pdf
 
Joanna and Chip Gaines and Michael Dubin got together recent.pdf
Joanna and Chip Gaines and Michael Dubin got together recent.pdfJoanna and Chip Gaines and Michael Dubin got together recent.pdf
Joanna and Chip Gaines and Michael Dubin got together recent.pdf
 
JKL Co issues zero coupon bonds on the market at a price of.pdf
JKL Co issues zero coupon bonds on the market at a price of.pdfJKL Co issues zero coupon bonds on the market at a price of.pdf
JKL Co issues zero coupon bonds on the market at a price of.pdf
 
Jill is offered a choice between receiving 50 with certaint.pdf
Jill is offered a choice between receiving 50 with certaint.pdfJill is offered a choice between receiving 50 with certaint.pdf
Jill is offered a choice between receiving 50 with certaint.pdf
 
Jennys Froyo INC Balance Sheet For Year Ended December 31.pdf
Jennys Froyo INC Balance Sheet For Year Ended December 31.pdfJennys Froyo INC Balance Sheet For Year Ended December 31.pdf
Jennys Froyo INC Balance Sheet For Year Ended December 31.pdf
 
Jim y Sue se iban a casar y estaban muy enamorados Antes de.pdf
Jim y Sue se iban a casar y estaban muy enamorados Antes de.pdfJim y Sue se iban a casar y estaban muy enamorados Antes de.pdf
Jim y Sue se iban a casar y estaban muy enamorados Antes de.pdf
 
Jhania Bive the muk hroutwes ite p+4i if peras bt in +45 te.pdf
Jhania Bive the muk hroutwes ite p+4i if peras bt in +45 te.pdfJhania Bive the muk hroutwes ite p+4i if peras bt in +45 te.pdf
Jhania Bive the muk hroutwes ite p+4i if peras bt in +45 te.pdf
 
JAVA Please help me on this method The requirement of the m.pdf
JAVA Please help me on this method The requirement of the m.pdfJAVA Please help me on this method The requirement of the m.pdf
JAVA Please help me on this method The requirement of the m.pdf
 
Jennifer invested the profit of his business in an investmen.pdf
Jennifer invested the profit of his business in an investmen.pdfJennifer invested the profit of his business in an investmen.pdf
Jennifer invested the profit of his business in an investmen.pdf
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

Java Programming Below are the lexerjava tokenjava and .pdf

  • 1. Java Programming: Below are the lexer.java, token.java, and shank.java. Shank.java is the main method file. The goal is to make sure to read the shank.txt file as a series of tokens & show the screenshot of shank.txt printed in console of eclipse. Make sure the lexer has all the state machines. Attached is rubric where all the required components a lexer must have. Attached is images of the errors the lexer has so make sure to fix those errors as well. Attached is image of how the output must be printed out as after all the errors are fixed. Lexer.java package mypack; import java.util.ArrayList; import java.util.List; import mypack.Token.TokenType; import java .util.HashMap; public class Lexer { private static final int INTEGER_STATE = 1; private static final int DECIMAL_STATE = 2; private static final int IDENTIFIER_STATE = 3; private static final int ERROR_STATE = 4; private static final int SYMBOL_STATE = 5; private static final int STRING_STATE = 6; private static final int CHAR_STATE = 7; private static final int COMMENT_STATE = 8; private static final char EOF = (char) -1; private static String input; private static int index; private static char currentChar; private static int lineNumber = 1; private static int indentLevel = 0; private static int lastIndentLevel = 0; private static HashMap<String, TokenType> keywords = new HashMap<String, TokenType>() {{ put("while", TokenType.WHILE); put("if", TokenType.IF); put("else", TokenType.ELSE); put("print", TokenType.PRINT); }}; private static HashMap<Character, TokenType> symbols = new HashMap<Character, TokenType>() {{ put('+', TokenType.PLUS); put('-', TokenType.MINUS); put('*', TokenType.MULTIPLY); put('/', TokenType.DIVIDE);
  • 2. put('=', TokenType.EQUALS); put(':', TokenType.COLON); put(';', TokenType.SEMICOLON); put('(', TokenType.LEFT_PAREN); put(')', TokenType.RIGHT_PAREN); put('{', TokenType.LEFT_BRACE); put('}', TokenType.RIGHT_BRACE); put('<', TokenType.LESS_THAN); put('>', TokenType.GREATER_THAN); }}; public Lexer(String input) { Lexer.input = input; index = 0; currentChar = input.charAt(index); } private void nextChar() { index++; if (index >= input.length()) { currentChar = EOF; } else { currentChar = input.charAt(index); } } private void skipWhiteSpace() { while (Character.isWhitespace(currentChar)) { nextChar(); } } private int getIndentLevel() { int level = 0; int i = index; char c = input.charAt(i); while (c == ' ' || c == 't') { if (c == 't') { level += 1; } else if (c == ' ') { level += 1; } i++; if (i >= input.length()) {
  • 3. break; } c = input.charAt(i); } return level; } public List<Token> lex(String inputString) throws Exception { input = inputString; index = 0; currentChar = input.charAt(index); List<Token> tokens = new ArrayList<Token>(); while (currentChar != EOF) { switch (currentState()) { case INTEGER_STATE: integerState(tokens); break; case DECIMAL_STATE: decimalState(tokens); break; case IDENTIFIER_STATE: identifierState(tokens); break; case ERROR_STATE: errorState(tokens); break; case SYMBOL_STATE: symbolState(tokens); break; case STRING_STATE: stringState(tokens); break; case CHAR_STATE: charState(tokens); break; case COMMENT_STATE: commentState(tokens); break; default: break; } } return tokens; } private void s (List<Token> tokens) {
  • 4. //TODO Auto-generated method stub } private static int currentState() { if (Character.isDigit(currentChar)) { return INTEGER_STATE; } else if (Character.isLetter(currentChar)) { return IDENTIFIER_STATE; } else if (currentChar == '.') { return DECIMAL_STATE; } else if (Character.isLetter(currentChar)) { return STRING_STATE; } else if (Character.isLetter(currentChar)) { return CHAR_STATE; }else if (Character.isLetter(currentChar)) { return COMMENT_STATE; }else if (Character.isDigit(currentChar)) { return SYMBOL_STATE; } else { return ERROR_STATE; } } private static void integerState(List<Token> tokens) { StringBuilder builder = new StringBuilder(); while (Character.isDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.NUMBER, builder.toString())); } private static void decimalState(List<Token> tokens) { StringBuilder builder = new StringBuilder(); builder.append(currentChar); advance(); while (Character.isDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.NUMBER, builder.toString())); } private static void identifierState(List<Token> tokens) {
  • 5. StringBuilder builder = new StringBuilder(); while (Character.isLetterOrDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.WORD, builder.toString())); } private static void errorState(List<Token> tokens) { StringBuilder builder = new StringBuilder(); while (Character.isLetterOrDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.WORD, builder.toString())); } private static void symbolState(List<Token> tokens) { StringBuilder builder = new StringBuilder(); while (Character.isLetterOrDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.SYMBOL, builder.toString())); } private static void stringState(List<Token> tokens) { StringBuilder builder = new StringBuilder(); while (Character.isLetterOrDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.WORD, builder.toString())); } private static void charState(List<Token> tokens) { StringBuilder builder = new StringBuilder(); while (Character.isLetterOrDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.WORD, builder.toString())); } private static void commentState(List<Token> tokens) {
  • 6. StringBuilder builder = new StringBuilder(); while (Character.isLetterOrDigit(currentChar)) { builder.append(currentChar); advance(); } tokens.add(new Token(Token.TokenType.WORD, builder.toString())); } private static void advance() { index++; if (index >= input.length()) { currentChar = EOF; } else { currentChar = input.charAt(index); } } } Token.java package mypack; public class Token { public enum TokenType { WORD, WHILE, IF, ELSE, NUMBER, SYMBOL, PLUS, MINUS, MULTIPLY, DIVIDE, EQUALS, COLON, SEMICOLON, LEFT_PAREN, RIGHT_PAREN, LEFT_BRACE, RIGHT_BRACE, LESS_THAN, GREATER_THAN, PRINT } public TokenType tokenType; private String value; public Token(TokenType type, String val) { this.tokenType = type; this.value = val; } public TokenType getTokenType() { return this.tokenType; } public String toString() { return this.tokenType + ": " + this.value; } }
  • 7. Shank.java package mypack; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class Shank { public static void main(String[] args) { Path filePath = Paths.get("shank.txt"); Charset charset = StandardCharsets.UTF_8; if (args.length != 1) { System.out.println("Error: Exactly one argument is required."); System.exit(0); } String filename = args[0]; try { List<String> lines = Files.readAllLines(Paths.get(filename)); for (String line : lines) { try { Lexer lexer = new Lexer(line); List<Token> tokens = lexer.lex(line); for (Token token : tokens) { System.out.println(token); } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } } catch (IOException e) { System.out.println("Error: Could not read file '" + filename + "'."); } } } shank.txt Fibonoacci (Iterative)
  • 8. define add (num1,num2:integer var sum : integer) variable counter : integer Finonacci(N) int N = 10; while counter < N define start () variables num1,num2,num3 : integer add num1,num2,var num3 {num1 and num2 are added together to get num3} num1 = num2; num2 = num3; counter = counter + 1; GCD (Recursive) define add (int a,int b : gcd) if b = 0 sum = a sum gcd(b, a % b) GCD (Iterative) define add (inta, intb : gcd) if a = 0 sum = b if b = 0 sum = a while counter a != b if a > b a = a - b; else b = b - a; sum = a; variables a,b : integer a = 60 b = 96 subtract a,b input. addnum1num2varnum3num1andnum2nreaddedtogethertogetnum3num1=num2num2= num3counter=counter+1GCDRecurgivedefineaddidentifieridentifieridentifieridentifieridentifier identifieridentifieridentifieridentifieridentifieridentifieridentifieridentifieridentifieridentifieroperator identifieridentifieroperatoridentifieridentifieroperatoridentifieroperatorintegerliternlidentifieridentifier keywordidentifierCompilation failed due to following error(s).