| Author |
Enum in java 1.4
|
deshdeep divakar
Ranch Hand
Joined: Apr 19, 2004
Posts: 91
|
|
Hi All, i have a method that returns string value and i want to use this string in the switch case. I tried using enum but it is not available in JAVA 1.4. can anbody suggest something.
|
"Do not be afraid of going slow, be afraid of standing still"
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
|
Please ask such non SCJP specific questions in our Java In General (intermediate) forum. Moving...
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
Originally posted by deshdeep divakar: Hi All, i have a method that returns string value and i want to use this string in the switch case. I tried using enum but it is not available in JAVA 1.4. can anbody suggest something.
You can only use integer values in switch statements. So if you must use a switch statement, you'll need to write some code to map your String to an integer value, and test that. Alternatively just use an if statement.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
deshdeep divakar
Ranch Hand
Joined: Apr 19, 2004
Posts: 91
|
|
|
i Cant use if else as the ladder will be too long. n how do i map it to integer. Cant i use Enumeration...???
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
i Cant use if else as the ladder will be too long
Will the switch statement not be of a simmilar length?
n how do i map it to integer.
Define a class which contains public static final integer values for each of the supported conditions and write method that takes a String and returns one of these integer values. You don;t need this though if you just use an if statement directly on the String value.
Cant i use Enumeration...???
No. An Enumeration is a legacy class for iterating through the values of a Vector or Hashtable. And enums are not available till JDK 1.5.
|
 |
Jaime M. Tovar
Ranch Hand
Joined: Mar 28, 2005
Posts: 133
|
|
|
There is not switch statement in java for Strings. But i think you can solve it using 'Chain of responsability' pattern if you have a lot of case statements. If you have just 3 or 4 case statements use if-then-else with the String.equals evaluation.
|
She will remember your heart when men are fairy tales in books written by rabbits.<br /> As long as there is duct tape... there is also hope.
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
I'm not sure how a Chain of Responsibility would fit here. But you could use a Command pattern, and put the commands in a map. Here's a quick example: Depending on what sorts of things you need to do here, you may want to define execute() with some arguments, or give it a non-void return type.
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Enum in java 1.4
|
|
|