如何从JOptionPane中的字符串数组中选择索引值 [英] How to select an index value from a String Array in a JOptionPane

查看:48
本文介绍了如何从JOptionPane中的字符串数组中选择索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个JOptionPane作为选择方法.我想要字符串数组的选择1,2或3的int值,因此可以将其用作计数器.如何获取数组的索引并将其设置为等于我的int变量loanChoice?

I've created a JOptionPane as a selection method. I want the int value for selection 1,2 or 3 of the String Array so I can use it as a counter. How do I get the index of the array and set it equal to my int variable 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().否则,您将不得不遍历选项数组以根据用户选择来查找索引.

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.

例如:

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

这篇关于如何从JOptionPane中的字符串数组中选择索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆