0

選択メソッドとして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 =**);
}
4

2 に答える 2

1

Tim Bender はすでに詳細な回答を提供しているので、コンパクト バージョンを次に示します。

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

showInputDialog(..)また、必ずしも文字列ではなく、オブジェクトの配列を取ることに注意してください。Loan オブジェクトがあり、toString()"Y.YY% で X 年" と言うメソッドを実装した場合、Loan の配列を指定して、おそらく配列インデックスをスキップして、選択した Loan に直接ジャンプすることができます。

于 2010-06-19T06:18:08.597 に答える
1

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;
 }
}
于 2010-06-19T06:04:18.130 に答える