How to return index of Object array used by JOptionPane for use in a switch statement?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 13:15:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!