我创建了一个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 =**);
}
答案 0 :(得分: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 :(得分:1)
由于蒂姆·本德已经给出了一个冗长的答案,这里是一个紧凑的版本。
int loanChoice = -1;
if (input != null) while (choices[++loanChoice] != input);
另外,请注意showInputDialog(..)
采用对象数组,而不是字符串。如果您有贷款对象并实施了他们的toString()
方法来说“X年在Y.YY%”,那么您可以提供一系列贷款,然后可能跳过数组索引并直接跳到选定的贷款。 / p>