Creating a List of Strings with "Attached" Methods

edited April 2017 in How To...

For a project I am creating a command prompt in which a user can enter commands, which cause code to run (what else would they do?). Right now I am using a list of if and if else statements which check the entered command. This is incredibly hard to work with, especially if I need to make changes. What I want to do is have it run through a list of commands. If it finds a match, it runs the block of code associated with that command. I'm currently thinking of a sort of HashMap that stores instructions rather than data. Is that possible, or will I need another way? As of right now, I don't know if it's possible to store instructions within a variable. Any help is greatly appreciated.

Answers

  • edited October 2013 Answer ✓

    The way you are doing it - using if-else statements - certainly works. There's no easy way to associate executable code with some data object.

    One way that might make it easier for you, however, is if you had a list of possible commands stored in an array, and a switch statement.

    Example:

    String[] cmds = {"look","get","move"};
    
    // When a command is entered:
    int caseNum = -1;
    String[] words = input.split(" ");
    for( int i=0; i < cmds; i++){
      if( words[0].equals(cmds[i]){
        caseNum = i;
      }
    }
    switch( caseNum ){
      case 0: // "look"
        println("You look. You see nothing. It is dark.");
        break;
      case 1: // "get"
        println("You get the " + words[1] );
        break;
      case 2: // "move"
        println("You try to move, but fail.");
        break;
      default:
        println("I didn't understand that.");
        break;
    }
    
  • edited October 2013

    "Store instructions within a variable"

    That's easy! It is called classes...

    You can do a simple class wrapping a String. If you define the toString() method to return the string, it will behave like a real one (almost).

    Otherwise, indeed, a HashMap might be a solution.

    For more precise answers, I suggest to do a very simple sketch illustrating what you want to do and how you are stuck. We can suggest ways to solve the problem.

  • The switch() seems like the best way to go for a command line. However, I forgot to mention that I plan on converting this over to a GUI after getting everything running, where a class with all the necessary methods would be stored. Thanks for your help, this information is a big help!

Sign In or Register to comment.