Here's pure Java 8 implementation:
import java.io.*;
import java.util.*;
import java.util.function.*;
public class Calculator {
Map<String, Integer> variables = new HashMap<>();
Map<String, Consumer<String>> commands = new HashMap<>();
Scanner scanner = new Scanner(System.in);
PrintStream out = System.out;
private Consumer<String> twoArgs(BiConsumer<String, String> bc) {
return args -> {
String[] fields = args.split(",\\s*", 2);
bc.accept(fields[0], fields[1]);
};
}
public Calculator() {
commands.put("READ", name -> variables.put(name, scanner.nextInt()));
commands.put("PRINT", name -> out.println(variables.get(name)));
commands.put("ADD", twoArgs((var1, var2) ->
variables.merge(var1, variables.getOrDefault(var2, 0), Integer::sum)));
}
public void process(BufferedReader input) {
input.lines()
.map(line -> line.split("\\s+", 2))
.filter(fields -> fields.length == 2)
.forEach(fields ->
commands.getOrDefault(fields[0].toUpperCase(), s -> {})
.accept(fields[1]));
}
public static void main(String[] args) {
new Calculator().process(new BufferedReader(new StringReader(
"READ A\nREAD B\n\n\nADD A, B\n\nPRINT A")));
}
}
We store variables in variables map (supposed that they are integers) and commands in commands map. The command accepts single string parameter and there's adapter method which may convert two parameter command (like ADD) into single parameter. You may add more commands in the constructor.
Update the main method to read the program source code from external file, resource, etc. Also note that this implementation has no error handling: incorrect input will be either ignored or lead to program crash.