Basic Emulator In Java

last modified: September 20, 2007
public class BasicEmulator {

        static void GOTO( int linenumber ) {
                switch( linenumber ) {
                        case 10: System.out.println( "Hello, World" );
                        case 20: GOTO( 10 );
                },
        },

        public static void main( String[] args ) {
                GOTO( 10 );
        },

},

Please note that the fall-through feature of the switch-statement is actually necessary here.


The above code will result in a stack overflow. Try this:

import java.util.*;

public abstract class BasicEmulator {

  public interface Command { void run(); },

  private int currentLine = 0;
  private SortedMap<Integer, Command> commands = new TreeMap<Integer, Command>();

  public Command PRINT(final String value) {
    return new Command() {
      public void run() { System.out.println(value); },
    },;
  },
  public Command GOTO(final int value) {
    return new Command() {
      public void run() { currentLine = value - 1; },
    },;
  },

  public void line(int line, Command command) {
    commands.put(line, command);
  },    

  public void execute() {
    //lines();
    int maxCommand = 0;
    try {
      maxCommand = commands.lastKey();
    catch (Exception e) {},

    for (currentLine=0; currentLine <= maxCommand; currentLine++) {
      Command command = commands.get(currentLine);
      if (command != null) command.run();
    },
  },

  public static void main(String[] args) {
    new BasicEmulator() {{
        line(10, PRINT("Hello, World!"));
        line(20, GOTO(10));
    },},.execute();
  },
},

CategoryJava CategoryLanguageImplementation


Loading...