如何从JOptionPane中的String数组中选择索引值

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

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 =**); } 

如果要返回选项的索引,可以使用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; } } 

蒂姆·本德已经给出了一个冗长的答案,这是一个紧凑的版本。

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

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