We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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
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:
"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!