Java 如何从JOptionPane中的字符串数组中选择索引值
我已经创建了一个JOptionPane作为选择方法。我想要字符串数组的选择1、2或3的int值,以便将其用作计数器。如何获取数组的索引并将其设置为int变量loanChoiceJava 如何从JOptionPane中的字符串数组中选择索引值,java,joptionpane,Java,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%"};
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;
}
}
public类选择loanchoices{
公共静态void main(最终字符串[]args){
最终字符串[]选项={“7年5.35%,“15年5.5%,“30年5.75%,”;
最终对象选择=JOptionPane.showInputDialog(空,“选择贷款”、“抵押选项”,
JOptionPane.QUESTION_消息,null,选项,选项[0]);
System.out.println(getChoiceIndex(choice,choices));
}
公共静态int-getChoiceIndex(最终对象选择,最终对象[]选择){
if(选项!=null){
for(int i=0;i
既然蒂姆·本德(Tim Bender)已经给出了详细的回答,下面是一个简洁的版本
int loanChoice = -1;
if (input != null) while (choices[++loanChoice] != input);
另外,请注意,
showInputDialog(..)
接受对象数组,而不一定是字符串。如果您有Loan对象,并且实现了它们的toString()
方法来表示“Y.YY%的X年”,那么您可以提供一个贷款数组,然后可能跳过数组索引,直接跳到所选贷款。欢迎使用。高亮显示代码并按ctrl-k键,使其正确渲染。