1

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);
4

1 回答 1

2

showInputDialog将返回用户输入的字符串,它是options数组中的字符串之一。知道选择了哪个索引的最短方法是在options数组上循环并找到相等性:

for(i = 0; i < options.length; i++) {
  if(options[i].equals(answer) {
    ansInt = i;
    break;
  }
}

另一种可能性是有一个键/值映射:

Map<String, Integer> optionsMap = new HashMap<String, Integer>();
options = optionsMap.keySet().toArray();
... Call the dialog ...
ansInt = optionsMap.get(answer);

如果选项数量较少,则第一个选项很好。如果您有很多选择,则第二种解决方案的性能会好很多。为了获得更好的性能,您可以缓存optionsMapandoptions数组。

于 2012-07-15T06:32:26.130 回答