Doubt with POO exercise in Java - problem with array

1

I have a question with an exercise that says: Create a Book class with loan, return and toString methods.

I want the vector to grow as the number of books grows, but in codigo.length , codigo appears as not being initialized. What am I doing wrong? Can someone help? Thanks!

private String titulo;
private String autor;
private String genero;
private static int codigo;
private static int stock=0;

 public Libro(String titulo, String autor, String genero, int codigo, int stock){

     this.titulo=titulo;
     generaCodigo();
     this.autor=autor;
     this.genero=genero;
 }

 public Libro(String titulo){

//El genera codigo me da error, me dice que cree un objeto

    this("titulo", "desconocido", "a confirmar", generaCodigo(), 0);

 }

public static void generaCodigo (){

//Acá me sale un error como que la variable codigo, en codigo.length no fue inicializada         

    int [] codigo = new int [codigo.length];

      for(int i=0; i>=codigo.length; i++){

         codigo[i]=i;
      }

      stock+=1
}
    
asked by Brenda Yanela Conzi 03.03.2018 в 23:39
source

2 answers

2

This line:

int [] codigo = new int [codigo.length];

It does not make sense because you're trying to create an array of unknown length. If you break that line in two, you will notice the error:

int [] codigo; //código está declarado pero no inicializado
codigo = new int [codigo.length];

You are asking that codigo be an array and that its length be equal to its current length. Since currently codigo does not exist, it does not have length.

    
answered by 04.03.2018 в 00:09
1

This line is wrong:

int [] codigo = new int [codigo.length];

You are giving it an unknown length, because the codigo attribute of your book class is never initialized. Another thing, do not use the same name of a class attribute for a local variable, because you do something called hide field and it's bad programming practice.

    
answered by 20.08.2018 в 21:52