Re: Simple question about Java Methods
On Mon, 18 Aug 2008, Mark Space wrote:
Danger_Duck wrote:
Alright, maybe someone can tell me how to do this with enums:
I have a combo-box (I'm using Eclipse, so
org.eclipse.swt.widgets.Combo.Combo) that contains the elements "Sin",
"Square", and "Sawtooth".
Based on the selection, I want to create a different function. This was
the original reason I was using public static final Strings instead of
enums: since the Combo.getText() method returns a String, I
I don't know SWT, but strings are easy to deal with:
Waves ws = Waves.valueOf("sine");
would get you the enum from the string, and:
Waves w = Waves.valueOf( combobox1.getText() );
Would do the same thing based on the code you have. (I changed the name from
a class to a variable because even though I don't know SWT I'm pretty sure
getText() is not a static method.)
Stefan is right, there's a better way besides a switch statement to do
actually draw the waveform. However, if you don't feel confortable yet
with adding methods to a Java enum, switch will work fine until you do.
Just be aware that there are other ways, and resolve to come back and
revist it when you feel more comfortable with Java.
Unless i missed that post, i don't think Stefan was actually suggesting
that. But whether it's his idea or yours, it is definitely the best way to
go. Like so:
public enum WaveType {
SINE ("sine") {public double evaluate(double x) {return Math.sin(x * 2.0 * Math.PI);}},
SQUARE ("square") {public double evaluate(double x) {return ((x % 1.0) < 0.5) ? -1.0 : 1.0;}};
// etc
public final String name ;
public WaveType(String name) {
this.name = name ;
}
public abstract double evaluate(double x) ;
public String toString() {
return name ;
}
}
Alternatively, factor the actual formulae out into static methods
somewhere, and call them from the evaluate implementations.
tom
--
1 pWN 3v3Ry+h1n G!!!1