Comment sélectionner une valeur d'index à partir d'un tableau dans une chaîne JOptionPane

StackOverflow https://stackoverflow.com/questions/3074478

  •  28-09-2019
  •  | 
  •  

Question

J'ai créé un JOptionPane comme méthode de sélection. Je veux la valeur int pour la sélection 1,2 ou 3 du tableau chaîne pour que je puisse l'utiliser comme un compteur. Comment puis-je obtenir l'index du tableau et Le mettre à mon loanChoice variable int?

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 =**);
}
Était-ce utile?

La solution

Vous pouvez utiliser JOptionPane.showOptionDialog() si vous voulez que l'index doit être retourné l'option. Dans le cas contraire, vous devrez parcourir le tableau d'options pour trouver l'indice en fonction de la sélection de l'utilisateur.

Par exemple:

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

Autres conseils

Depuis Tim Bender a déjà donné une réponse verbeux, voici une version compacte.

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

En outre, notez que showInputDialog(..) prend un tableau d'objets, pas nécessairement des chaînes. Si vous aviez des objets prêt et mis en œuvre leurs méthodes de toString() dire « X années à Y.YY% » alors vous pouvez fournir un tableau de prêts, puis passez probablement l'index de tableau et juste sauter droit au prêt sélectionné.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top