gpt4 book ai didi

java - 如何从 JOptionPane 中的字符串数组中选择索引值

转载 作者:行者123 更新时间:2023-12-02 08:32:08 25 4
gpt4 key购买 nike

我创建了一个 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;
}
}

关于java - 如何从 JOptionPane 中的字符串数组中选择索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com