Re: Alternative to if...else for keyword based actions
c0balt279@gmail.com wrote:
I was wondering if there is an alternative to if...else and
switch(case) where you don't have to define the results. For example,
....
String token = "println";
String parameter = "Hello World";
You might consider making your tokens Enums. Define an abstract method
in the Enum, and override it for each enum to "do something." Here's a
longer link:
<http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html>
Example: I only implemented the println method, the rest are just
stubbed out because I'm lazy. Exercise for the reader, and all that.
package enumtokentest;
public class Main {
public static void main(String[] args) {
String token = "println";
String param = "Hello World!";
Tokens t = Tokens.valueOf( token.toUpperCase() );
t.eval( param );
}
}
enum Tokens
{
ADD { public Object eval( Object ... paramList) { return 1;} },
MULTIPLY { public Object eval( Object ... paramList) {return 1;} },
DIVIDE { public Object eval( Object ... paramList) {return 1;} },
SUBTRACT { public Object eval( Object ... paramList) {return 1;} },
PRINTLN {
@Override
public Object eval(Object... paramList) {
for (Object o : paramList) {
System.out.print(o);
}
System.out.println("");
return 1;
}
};
abstract public Object eval( Object ... paramList );
}