Problem with array in Java

Asked

Viewed 377 times

-1

I am trying to create a calendar of contacts in java, I am using some classes that were requested in the exercise.

the main class:

    import java.util.Scanner;

    public class Lista15Q03 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int max = 3;

        Endereco end[] = new Endereco[max];

        Telefones tel[] = new Telefones[max];

        Emails email[] = new Emails[max];

        Contatos con[] = new Contatos[max];
        Contatos c = new Contatos();
        c.setEndereco(end);

        int op;
        int indice = 0;

        do {

            System.out.println("1 - adicionar");
            System.out.println("2 - listar");
            System.out.println("3 - mostrar");
            System.out.println("4 - alterar");
            System.out.println("5 - apagar");
            System.out.println("6 - sair");
            System.out.print("escolha: ");
            op = scan.nextInt();

            switch(op){
                case 1:
                    if(indice < max){

                        c = new Contatos();

                        System.out.println("nome: ");
                        String nome = scan.next();
                        c.setNome(nome);

                        System.out.print("nome da rua: ");
                        String rua = scan.next();
                        end[indice].setRua(rua);

                        System.out.print("número: ");
                        String num = scan.next();
                        end[indice].setNumero(num);

                        System.out.print("bairro: ");
                        String bairro = scan.next();
                        end[indice].setRua(bairro);

                        con[indice] = c;
                        indice++;
                    }else{
                        System.out.println("");
                        System.out.println("lista de contatos cheia");
                        System.out.println("");
                    }
                    break;
                case 2:
                    break;
                case 6:
                    break;
                default:
                    System.out.println("opção inválida");
            }

        } while (op != 6);

    }

}

the class of contacts:

public class Contatos {
    private String nome;
    private Endereco[] endereco;
    private Emails[] email;
    private Telefones[] telefones;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Endereco[] getEndereco(){
        return endereco;
    }

    public void setEndereco(Endereco[] endereco){
        this.endereco = endereco;
    }

    public Emails[] getEmail() {
        return email;
    }

    public void setEmail(Emails[] email) {
        this.email = email;
    }

    public Telefones[] getTelefones() {
        return telefones;
    }

    public void setTelefones(Telefones[] telefones) {
        this.telefones = telefones;
    }

}

error running on terminal:

Exception in thread "main" java.lang.Nullpointerexception At lista15q03.main(Lista15q03.java:46)

error running in netbeans:

Exception in thread "main" java.lang.NullPointerException
    at lista15q03.Lista15Q03.main(Lista15Q03.java:41)
/home/henrique/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 5 segundos)
  • 1

    Where is line 46?

  • Put the full stack trace.

  • It could further detail the project and where the problem occurs?

  • line 46 is this: end[Indice]. setRua(street);

  • The two errors occur in different lines, one says line 41 and another 43

  • I have to create an agenda with crud functionality, so I created 4 classes, Email, Phones, Address and Contacts. I refer to other classes in the contacts class as array. In the main class of the program, I instate the Contacts class and also play it within the array.

  • That’s why in netbeans you have the package line and in sublime you don’t. So the error is really from this snippet: end[Indice]. setRua(street);

  • 1

    This vector input was not initialized, you just initialized it as an array, but not individually

  • 1

    You have created an address array but the vector has no address type object. So you are accessing an empty array. This is why nullpointer occurs.

  • then in case I have to instantiate Address and throw the object in c.setEndereco(); ?

Show 5 more comments

3 answers

1

Missing you instantiate the objects in the arrays positions end[], tel[], email.

On calls

Endereco end[] = new Endereco[max];

Telefones tel[] = new Telefones[max];

Emails email[] = new Emails[max];

Only the array of each of these objects with operator were instantiated new.

For each array vc needs a for that traverses the entire array instantiating the objects

As in the example below

  for (int i = 0; i < max; i++) {
            end[i] = new Endereco();
        }

However, I note that the objects Addressee, Emails, and Phones are already class attributes Contacts. In this way, a more correct way would be to remove them from the main class and add a method for initializing these objects in their own classes. As in the example below.

public class Contatos {

    int max;
    private String nome;
    private Endereco[] endereco;
    private Emails[] email;
    private Telefones[] telefones;

    public Contatos(int max) {
        this.max = max;
        initEnderecos();
   }

    public String getNome() {
        return nome;
   }

    public void setNome(String nome) {
        this.nome = nome;
   }

    public Endereco[] getEndereco() {
       return endereco;
   }

    public void setEndereco(Endereco[] endereco) {
        this.endereco = endereco;
  }

    public Emails[] getEmail() {
        return email;
  }

    public void setEmail(Emails[] email) {
       this.email = email;
  } 

    public Telefones[] getTelefones() {
       return telefones;
  }

   public void setTelefones(Telefones[] telefones) {
      this.telefones = telefones;
  }

   private void initEnderecos() {
        for (int i = 0; i < max; i++) {
            this.endereco[i] = new Endereco();
        }
   }
} 

In this example I moved the attribute max, which is the maximum size of the contact list for the class Contato and initialize only the array of Endereco. The other vc can do similarly.

Note that, this is just one of the improvements you can make in this code

  • I will try to implement this, already put result, but already thank.

  • Thank you for the answer. I will succeed with the answer from the partner up there, I will try to implement these tips later. vlw.

  • All right, the answer I posted was just to solve this problem. I identified some other problems in the code, however I solved only the problem related to doubt.

1

Hello, the problem that is happening is that it was just declaring the value for array as new Address, however each item of it is null until initialized, so you will have to do this initialization before adhering values to the variables of this object.

 switch(op){
             case 1:
                 if(indice < max){

                     end[indice] = new Endereco();
                     c = new Contato();

                     System.out.println("nome: ");
                     String nome = scan.next();
                     c.setNome(nome);

                     System.out.print("nome da rua: ");
                     String rua = scan.next();
                     end[indice].setRua(rua);

                     System.out.print("número: ");
                     String num = scan.next();
                     end[indice].setNumero(num);

                     System.out.print("bairro: ");
                     String bairro = scan.next();
                     end[indice].setBairro(bairro);

                     c.setEndereco(end);
                     con[indice] = c;
                     indice++;
                 }

Another thing that I noticed by analyzing your code is that arrow an address in object c, however dps initializes it again, losing what was set that in the case had nothing, the most correct thing to do is just put this value after entering all the items of the address, and tbm was putting the value of the neighborhood on the street.

  • kk Valeu, had not even noticed that part of the value of the neighborhood on the street. Very simple resolution, thank you beast. : ) I think I remember you from another earlier doubt of Java tbm kk vlw o/

  • kkkkkk, Usually the mistakes they give are very simple, the bad thing is to find.

1

If I may use List, do that you will be happier, if you cannot, you will have to create an object for each Array you created, because each position of the Array is waiting for an object and you are passing a String. then in your case it would look like this.

BS: I will do only with one of the Array and you replicate.

Endereco []end = new Endereco[max]; // cada posição tem que ser um objeto
Endereco endereco = new Endereco();

System.out.print("nome da rua: ");
String rua = scan.next();
endereco.setRua(rua);
end[indice] = endereco;

end[indice].getRua(); //para mostrar o valor depois.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.