I am repeatedly verified by an array


I'm sure I have some silly mistake but I can not see what it is ..

My idea is that I extract a data from a TxtPanel. Check if that data is in an array. If it is inside the if and does several things, it will get an error message.

But I do not know why this is done to me twice. Can you help me?

Code is:

// Acció button Aceptar
class  BtnAceptar implements ActionListener {

     public void actionPerformed(ActionEvent e) {
         //Creem les variables que utilitzem per registrar usuaris etc.. // Pendent BASE DE DADES
         String usuariExisteix = txtUsuari2.getText(); // la dada que ha introduït l'usuari:                
         String[] usuarisPermesos = new String[] {"administrador", "professor"}; // Array amb usuaris

         // Recorrem l'array per guardar-los a una variable nova. 
         for(int i =0; i<usuarisPermesos.length; i++) {
             String usuari = usuarisPermesos[i];

             //Si l'usuari existeix entrem dins sino avise'm que no el tenim a la BD.

                // si l'usuari existeix i es professor llavors obra la pantalla professor.
                 if(usuari.equalsIgnoreCase("professor")) {
                     pantalla_professor v2 = new pantalla_professor(); // truquem la pantalla que volem anar
                     v2.setVisible(true); // La fem visible
                     dispose(); // així tanquem la finestra
                 } else {
                     // si l'usuari es administrador llavors obra la pantalla administrador.
                     Pantalla_admin v3 = new Pantalla_admin(); // truquem la pantalla que volem anar
                     v3.setVisible(true); // La fem visible
                     dispose(); // així tanquem la finestra
             } else {
                 JOptionPane.showMessageDialog(null, "No existe el usuario.");
asked by Montse Mkd 25.10.2018 в 10:48

1 answer


Generalizing a little, you have a list of objects and you want to check if a given object is in the list.

The current problem is that for each object in the list you see if it is the one you want and if it is not, you show a message, but what you should do is look until you find one that matches or, if there is none, you arrive at the end of the list:

boolean encontrado=false;
for (elemento: listaElementos) {
   if (elemento.equals(elementoComparado)) {
       break; //no buscamos más
if (!encontrado) {
  //mostramos mensaje 
answered by 25.10.2018 / 12:22