[英]How to select an index value from a String Array in a JOptionPane
我创建了一个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;
}
}
由于Tim Bender已经给出了详细的答案,因此这是一个紧凑的版本。
int loanChoice = -1;
if (input != null) while (choices[++loanChoice] != input);
另外,请注意showInputDialog(..)
接受对象数组,不一定是字符串。 如果您有Loan对象并实现其toString()
方法说“ X years at Y.YY%”,那么您可以提供一个Loans数组,然后可能跳过该数组索引,而直接跳至所选的Loan。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.