FOR expression does not recognize Object Array

0

In a login system with graphical interface I created a Class User whose attributes are (String user, String pass), then in the Mail (main) I hardcode an array of users (listUser []) with 3 users with their respective passwords .

When raising the function to validate "user" the compiler does not recognize "i

asked by Die Duro 19.08.2017 в 21:45
source

2 answers

2

Just put it like that.

  public boolean userok(){
        boolean userOk=false;
        for(int i=0;i<=listaUser.length-1;i++){  ///solamente quité los corchetes.
            if (listaUser[i].getUser().equals(txt_user.getText())){
                userOk=true;
            }   
        }
        return userOk;
    }

The brackets are only used when you want to access an element of the arrangement, in this case it is not necessary.

    
answered by 19.08.2017 / 22:20
source
2

Two errors:

  • The error message comes out because listaUser is defined as a local variable in the principal method. As such, it is only available within that method; the code of another method simply can not access this variable and therefore the error. When the method is executed, the array exists while it is not exited; at the end of the execution of the method the variable "goes out of scope", the array is left without any reference that uses it and at any moment the garbage collector can delete it.

    The most obvious solution is to define listaUser as a member of the class:

    public class Principal { // El nombre de la clase siempre va en mayúsculas !!
       private User listaUser[];
    
       public Principal() { // El nombre de la clase siempre va en mayúsculas !!
          ...
          this.listaUser = new User[3];  // Realmente el this no es necesario, pero opino que ayuda a visualizar que la variable es un miembro de la clase.
          this.listaUser[0]= new User("dieduro", "codoacodo");
          ...
    

    As a member of the class,'listUser' will be visible to the other methods of the class.

  • As FrEqDE says, it should be i<=this.listaUser.length . Although listaUser is an array, brackets are only used when you want to access an element of it; the other methods and attributes are referenced without the brackets. This error is not related to the error message but it would have come later.

answered by 19.08.2017 в 23:54