SlideShare a Scribd company logo
1 of 8
Download to read offline
Java Programming: Below are the lexer, token, and shank files with the shank.txt. Fix any error in
the files but make sure the shank.txt is being printed out in the terminal of eclipse. Show the full
code for all three files along with the screenshot of shank.txt being read in the terminal. Attached is
the rubric.
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) {
}
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,
ENDOFLINE, MODULUS
}
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

More Related Content

Similar to Java Programming Below are the lexer token and shank file.pdf

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
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
ezonesolutions
 
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
 
Java Programming Introduction Lexer 1 In this project we.pdf
Java Programming  Introduction Lexer 1 In this project we.pdfJava Programming  Introduction Lexer 1 In this project we.pdf
Java Programming Introduction Lexer 1 In this project we.pdf
adinathassociates
 

Similar to Java Programming Below are the lexer token and shank file.pdf (20)

java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
Templates
TemplatesTemplates
Templates
 
Assignment
AssignmentAssignment
Assignment
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
core java
 core java core java
core java
 
DataTypes.ppt
DataTypes.pptDataTypes.ppt
DataTypes.ppt
 
Functional concepts in C#
Functional concepts in C#Functional concepts in C#
Functional concepts in C#
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Generating parsers using Ragel and Lemon
Generating parsers using Ragel and LemonGenerating parsers using Ragel and Lemon
Generating parsers using Ragel and Lemon
 
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
 
Java Programming Introduction Lexer 1 In this project we.pdf
Java Programming  Introduction Lexer 1 In this project we.pdfJava Programming  Introduction Lexer 1 In this project we.pdf
Java Programming Introduction Lexer 1 In this project we.pdf
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 

More from abdulkadar1977

Research Project Community Assessment Report Purpose For .pdf
Research Project  Community Assessment Report Purpose For .pdfResearch Project  Community Assessment Report Purpose For .pdf
Research Project Community Assessment Report Purpose For .pdf
abdulkadar1977
 
Revise el siguiente estudio de caso y luego responda las pre.pdf
Revise el siguiente estudio de caso y luego responda las pre.pdfRevise el siguiente estudio de caso y luego responda las pre.pdf
Revise el siguiente estudio de caso y luego responda las pre.pdf
abdulkadar1977
 

More from abdulkadar1977 (20)

Which of the following is a control right 1 Shareholders .pdf
Which of the following is a control right 1 Shareholders .pdfWhich of the following is a control right 1 Shareholders .pdf
Which of the following is a control right 1 Shareholders .pdf
 
What is politics What makes a decision political How do we.pdf
What is politics What makes a decision political How do we.pdfWhat is politics What makes a decision political How do we.pdf
What is politics What makes a decision political How do we.pdf
 
Suppose X and Y are independent and identically distributed .pdf
Suppose X and Y are independent and identically distributed .pdfSuppose X and Y are independent and identically distributed .pdf
Suppose X and Y are independent and identically distributed .pdf
 
Un comit tiene trece trece miembros Hay tres tres miembros.pdf
Un comit tiene trece trece miembros Hay tres tres miembros.pdfUn comit tiene trece trece miembros Hay tres tres miembros.pdf
Un comit tiene trece trece miembros Hay tres tres miembros.pdf
 
The following is a set of data for a population with N10 1.pdf
The following is a set of data for a population with N10 1.pdfThe following is a set of data for a population with N10 1.pdf
The following is a set of data for a population with N10 1.pdf
 
Step Minerals Removed Rock Name 4 example olivine forster.pdf
Step Minerals Removed Rock Name 4 example olivine forster.pdfStep Minerals Removed Rock Name 4 example olivine forster.pdf
Step Minerals Removed Rock Name 4 example olivine forster.pdf
 
The Federal Deposit Insurance Corporation FDIC is a US c.pdf
The Federal Deposit Insurance Corporation FDIC is a US c.pdfThe Federal Deposit Insurance Corporation FDIC is a US c.pdf
The Federal Deposit Insurance Corporation FDIC is a US c.pdf
 
Solve it using Ubuntu Homework 1 Modify the script for_loop.pdf
Solve it using Ubuntu Homework 1 Modify the script for_loop.pdfSolve it using Ubuntu Homework 1 Modify the script for_loop.pdf
Solve it using Ubuntu Homework 1 Modify the script for_loop.pdf
 
Research Project Community Assessment Report Purpose For .pdf
Research Project  Community Assessment Report Purpose For .pdfResearch Project  Community Assessment Report Purpose For .pdf
Research Project Community Assessment Report Purpose For .pdf
 
Select al the examples of Sexual Reproduction A Ecoli is a .pdf
Select al the examples of Sexual Reproduction A Ecoli is a .pdfSelect al the examples of Sexual Reproduction A Ecoli is a .pdf
Select al the examples of Sexual Reproduction A Ecoli is a .pdf
 
Revise el siguiente estudio de caso y luego responda las pre.pdf
Revise el siguiente estudio de caso y luego responda las pre.pdfRevise el siguiente estudio de caso y luego responda las pre.pdf
Revise el siguiente estudio de caso y luego responda las pre.pdf
 
Muscle contractions are driven by motor proteins What inter.pdf
Muscle contractions are driven by motor proteins What inter.pdfMuscle contractions are driven by motor proteins What inter.pdf
Muscle contractions are driven by motor proteins What inter.pdf
 
please write all your steps on the paper 1 Economists are .pdf
please write all your steps on the paper 1 Economists are .pdfplease write all your steps on the paper 1 Economists are .pdf
please write all your steps on the paper 1 Economists are .pdf
 
Londra Belediye Bakan Tate Modernin kamu finansmann artrma.pdf
Londra Belediye Bakan Tate Modernin kamu finansmann artrma.pdfLondra Belediye Bakan Tate Modernin kamu finansmann artrma.pdf
Londra Belediye Bakan Tate Modernin kamu finansmann artrma.pdf
 
Q8Rehan Shrcyas and Darsan each value police protection .pdf
Q8Rehan Shrcyas and Darsan each value police protection .pdfQ8Rehan Shrcyas and Darsan each value police protection .pdf
Q8Rehan Shrcyas and Darsan each value police protection .pdf
 
Describe the correct use of equipment to accurately measure.pdf
Describe the correct use of equipment to accurately measure.pdfDescribe the correct use of equipment to accurately measure.pdf
Describe the correct use of equipment to accurately measure.pdf
 
7214 Exercise 6312 Continued Let X1Xn be iid having.pdf
7214 Exercise 6312 Continued Let X1Xn be iid having.pdf7214 Exercise 6312 Continued Let X1Xn be iid having.pdf
7214 Exercise 6312 Continued Let X1Xn be iid having.pdf
 
2 Interview an older adult near retirement age to see how t.pdf
2 Interview an older adult near retirement age to see how t.pdf2 Interview an older adult near retirement age to see how t.pdf
2 Interview an older adult near retirement age to see how t.pdf
 
1 Private label merchandise should be displayed to the left.pdf
1 Private label merchandise should be displayed to the left.pdf1 Private label merchandise should be displayed to the left.pdf
1 Private label merchandise should be displayed to the left.pdf
 
Aadaki paragraf pasif sesi her paragrafta aktif sese evire.pdf
Aadaki paragraf pasif sesi her paragrafta aktif sese evire.pdfAadaki paragraf pasif sesi her paragrafta aktif sese evire.pdf
Aadaki paragraf pasif sesi her paragrafta aktif sese evire.pdf
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
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
 

Recently uploaded (20)

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
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
 
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
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
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...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.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...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
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
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
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
 

Java Programming Below are the lexer token and shank file.pdf

  • 1. Java Programming: Below are the lexer, token, and shank files with the shank.txt. Fix any error in the files but make sure the shank.txt is being printed out in the terminal of eclipse. Show the full code for all three files along with the screenshot of shank.txt being read in the terminal. Attached is the rubric. 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);
  • 2. 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; }
  • 3. 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) { } private static int currentState() { if (Character.isDigit(currentChar)) { return INTEGER_STATE; } else if (Character.isLetter(currentChar)) { return IDENTIFIER_STATE; } else if (currentChar == '.') {
  • 4. 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();
  • 5. } 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); }
  • 6. } } 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, ENDOFLINE, MODULUS } 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) {
  • 7. 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)
  • 8. 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