In: Computer Science
Create an ID table class that maps identifiers to memory addresses for a Parser java program. The first identifier will be at address 0, the second at address 1, and so on.
I am working on a Lexer/Parser project for java. I've completed the lexer and parser portion of the program but I'm looking for some assistance in creating a ID table class.
That has specific methods that add token identifiers into a hashmap.
Here are the specifications that I'm looking for assistance with.
Define the class IdTable with the following data members and methods:
a) a hashmap data member with String key and integer value. The keys are the identifiers and the values represent the address in memory in which the identifier will be stored. Assign the index for each entry such that the first id will have address 0, second id will have address 1 and so on
b) add - this method adds an entry to the map, you need only send the id.
c) getAddress - this method returns the address associated with an id, or -1 if not found.
d) toString method that prints the string values of the hashmap.
Here is my code so far. Mainly need help with b and c. Thank you for your assistance. I Will like and comment.
import java.util.HashMap; public class IdTable { public String key; public int value; // create hashmap type data member HashMap<String, Integer> table = new HashMap<String,Integer>(); // todo create add method public void add() { } //todo create get address method // write toString method for ID table @Override public String toString() { return "IdTable{" + "table=" + table + '}'; } }
Program Code Screenshot :
Sample Output :
Program Code to Copy
import java.util.HashMap; class IdTable { //Variable to keep track of addresses private int address = 0; // create hashmap type data member HashMap<String, Integer> table = new HashMap<String, Integer>(); // todo create add method public void add(String id) { //Add id to the map with the current address. Increment the address table.put(id, address++); } public int getAddress(String id) { //Return the address for the given return table.get(id); } //todo create get address method // write toString method for ID table @Override public String toString() { return "IdTable{" + "table=" + table + '}'; } } class Main{ public static void main(String[] args) { IdTable table = new IdTable(); table.add("name"); table.add("section"); table.add("grade"); System.out.println("Address of 'section' is "+table.getAddress("section")); System.out.println(table); } }