簡體   English   中英

如何從JOptionPane中的字符串數組中選擇索引值

[英]How to select an index value from a String Array in a 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%"};
        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;
 }
}

由於Tim Bender已經給出了詳細的答案,因此這是一個緊湊的版本。

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

另外,請注意showInputDialog(..)接受對象數組,不一定是字符串。 如果您有Loan對象並實現其toString()方法說“ X years at Y.YY%”,那么您可以提供一個Loans數組,然后可能跳過該數組索引,而直接跳至所選的Loan。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM