Query on conversion between String to Enum type
800808Sep 27 2010 — edited Sep 29 2010Hi All,
I would like to get advice on how to convert between char and Enum type. Below is an example of generating unique random alphabet letters before converting them back to their corresponding letters that belonged to enum type called definition.Alphabet, which is part of a global project used by other applications:
package definition;
public enum Alphabet
{
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S,
T, U, V, W, X, Y, Z
}
public StringBuffer uniqueRandomAlphabet()
{
String currentAlphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuffer randomAlphabetSB = new StringBuffer();
for (int numberOfAlphabet=26; numberOfAlphabet>0; numberOfAlphabet--)
{
int character=(int)(Math.random()* numberOfAlphabet);
String characterPicked = currentAlphabet.substring(character, character+1);
// System.out.println(characterPicked);
randomAlphabetSB.append(characterPicked);
StringBuffer remainingAlphabet = new StringBuffer( currentAlphabet.length() );
remainingAlphabet.setLength( currentAlphabet.length() );
int current = 0;
for (int currentAlphabetIndex = 0; currentAlphabetIndex < currentAlphabet.length(); currentAlphabetIndex++)
{
char cur = currentAlphabet.charAt(currentAlphabetIndex);
if (cur != characterPicked.charAt(0))
remainingAlphabet.setCharAt( current++, cur );
}
currentAlphabet = remainingAlphabet.toString();
}
return randomAlphabetSB;
// System.out.println(randomAlphabetSB);
}
I got the following compilation error when trying to pass (Alphabet) StringBuffer[0] to a method that expects Alphabet.A type:
inconvertible types
required: definition.Alphabet
found: char
Any ideas on how to get around this. An alternative solution is to have a huge switch statement to assemble Alphabet type into an ArrayList<Alphabet>() but wondering whether there is a more shorter direct conversion path.
I am using JDK1.6.0_17, Netbeans 6.7 on Windows XP.
Thanks a lot,
Jack