我怎樣才能提取選定的值?我的意思是如果用戶選擇了“Vital”,我需要為“Olympic”獲取值 0 或值 1
Object[] possibleValues = { "Vital", "Olympic", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
我有一個以前的代碼,它與 showConfirmDialog 框一起作業得很好。
int choice = JOptionPane.showConfirmDialog(null, "Click Yes for Rectangles, No for Ovals");
if (choice==2)
{
return ;
}
if (choice==0)
{
choice=5;
}
if (choice==1)
{
choice=6;
}
Shapes1 panel = new Shapes1(choice);
這作業得很好。
uj5u.com熱心網友回復:
如果它為您提供文本表示,請添加一種方法將文本值轉換為數字索引(如果這是您需要的)。如果這些值是常量,則 O(1) 執行此操作的方法是提前創建地圖:
Map<String, Integer> valueToIndex = new HashMap<>();
valueToIndex.put("Vital", 0);
valueToIndex.put("Olympic", 1);
valueToIndex.put("Third", 2);
那么它只是
int index = valueToIndex.get((String) selectedValue)
相反,如果它是您只會做一次的事情,請不要費心創建地圖。只需迭代可能的值,直到找到selectedValue
int indexFor(Object selectedValue, Object possibleValues) {
for (int i = 0; i < possibleValues.length; i ) {
if (possibleValues[i].equals(selectedValue)) {
return i;
}
}
throw new RuntimeException("No index found for " selectedValue);
}
然后呼叫這個方法:
int index = indexFor(selectedValue, possibleValues);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/359098.html
