问题
I am experimenting with variations on the dialog box tutorial on Oracle. I felt that the number of options I offered resulted in too many buttons so I converted from OptionDialog to InputDialog and used an Object array. Now, however, my switch statement (in replyMessage) doesn't work because of the change in data type. How do I get the index in the Object array corresponding to the user's selection?
Object answer;
int ansInt;//the user'a answer stored as an int
Object[] options = {"Yes, please",
"No, thanks",
"No eggs, no ham!",
"Something else",
"Nothing really"
};//end options
answer = JOptionPane.showInputDialog(null, "Would you like some green eggs to go with that ham?",
"A Silly Question",
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
ansInt = ;//supposed to be the index of user's seleection
replyMessage(ansInt);
回答1:
showInputDialog
will return the string that the user entered, which is one of the strings in the options
array. The shortest way to know which index was selected is to loop on the options
array and find equality:
for(i = 0; i < options.length; i++) {
if(options[i].equals(answer) {
ansInt = i;
break;
}
}
Another possibility is to have a map of key/values:
Map<String, Integer> optionsMap = new HashMap<String, Integer>();
options = optionsMap.keySet().toArray();
... Call the dialog ...
ansInt = optionsMap.get(answer);
The first option is good if the number of options is low. If you have many options, the second solution will perform a lot better. For even better performance, you can cache theoptionsMap
and options
array.
来源:https://stackoverflow.com/questions/11489845/how-to-return-index-of-object-array-used-by-joptionpane-for-use-in-a-switch-stat