Skip to content
Snippets Groups Projects
Commit ed537859 authored by jm15g21's avatar jm15g21
Browse files

Upload New File

parent 544d600a
Branches
No related tags found
No related merge requests found
package Managers;
import java.util.Hashtable;
import java.util.Stack;
public class ScopeManager implements IManager {
public Stack<Hashtable<String, Integer>> getScopedVariables() {
return scopedVariables;
}
//This method works until we introduce classes down the line
//At that point classes will need their own scope manager somehow
private Stack<Hashtable<String, Integer>> scopedVariables = new Stack<>();
public void enterLocalScope() {
scopedVariables.push(new Hashtable<>());
System.out.println("Entered local scope");
}
public void leaveLocalScope() {
scopedVariables.pop();
System.out.println("Left local scope");
}
/**
* Gets all currently accessible variables.
*/
public Hashtable<String, Integer> getAllVariables() {
Hashtable<String, Integer> output = new Hashtable<>();
for (Hashtable<String, Integer> scopeLevel : scopedVariables) {
output.putAll(scopeLevel);
}
return output;
}
public void modifyVariable(String varName, int newValue) {
//Locate the variable, if it exists modify it otherwise create it in the current scope
for (Hashtable<String, Integer> scopeLevel : scopedVariables) {
//It exists
if (scopeLevel.containsKey(varName)) {
scopeLevel.replace(varName, newValue);
return;
}
}
//It doesn't exist
scopedVariables.peek().put(varName, newValue);
}
public void removeVariable(String varName) {
for (Hashtable<String, Integer> scopeLevel : scopedVariables) {
if (scopeLevel.containsKey(varName)) {
scopeLevel.remove(varName);
}
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment