2010-06-19 48 views
0

我已经创建了一个JOptionPane作为选择方法。我想为字符串数组的选择1,2或3的int值,所以我可以用它作为计数器。我如何获得数组的索引并将其设置为等于我的整型变量loanChoice?如何从JOptionPane中的字符串数组中选择一个索引值

public class SelectLoanChoices { 
    int loanChoice = 0; 
    String[] choices = {"7 years at 5.35%", "15 years at 5.5%", 
      "30 years at 5.75%"}; 
     String input = (String) javax.swing.JOptionPane.showInputDialog(null, "Select a Loan" 
       ,"Mortgage Options",JOptionPane.QUESTION_MESSAGE, null, 
       choices, 
       choices[0] 
       **loanChoice =**); 
} 
+1

欢迎来到SO。突出显示代码并按下ctrl-k,以便正确渲染。 – bernie 2010-06-19 05:33:37

回答

1

如果您想要返回选项的索引,则可以使用JOptionPane.showOptionDialog()。否则,您必须遍历选项数组才能找到基于用户选择的索引。

例如:

public class SelectLoanChoices { 
public static void main(final String[] args) { 
    final String[] choices = { "7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%" }; 
    final Object choice = JOptionPane.showInputDialog(null, "Select a Loan", "Mortgage Options", 
    JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]); 
    System.out.println(getChoiceIndex(choice, choices)); 

} 

public static int getChoiceIndex(final Object choice, final Object[] choices) { 
    if (choice != null) { 
    for (int i = 0; i < choices.length; i++) { 
    if (choice.equals(choices[i])) { 
    return i; 
    } 
    } 
    } 
    return -1; 
} 
} 
1

由于蒂姆·本德已经做了详细的回答,这里是一个压缩版本。

int loanChoice = -1; 
if (input != null) while (choices[++loanChoice] != input);

此外,请注意采用showInputDialog(..)对象数组,不一定字符串。如果你有贷款对象,并实施他们的toString()方法来说“在Y.YY%的X年”,那么你可以提供一个贷款数组,然后可能跳过数组索引,并直接跳到选定的贷款。

相关问题