How to select an index value from a String Array in a JOptionPane

北战南征 提交于 2019-12-02 09:01:19

You can use JOptionPane.showOptionDialog() if you want the index of the option to be returned. Otherwise, you will have to iterate through the option array to find the index based on the user selection.

For instance:

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;
 }
}

Since Tim Bender already gave a verbose answer, here's a compact version.

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

Also, note that showInputDialog(..) takes an array of Objects, not necessarily strings. If you had Loan objects and implemented their toString() methods to say "X years at Y.YY%" then you could supply an array of Loans, then probably skip the array index and just jump right to the selected Loan.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!