Print object from an arraylist [duplicate]

0

When trying to print the list of objects I get the error of java.lang.NullPointerException

public Productos(int id, int precio, String nombre) {
    this.id = id;
    this.precio = precio;
    this.nombre = nombre;
}

public int getId() {
    return id;
}

public int getPrecio() {
    return precio;
}

public String getNombre() {
    return nombre;
}

 @Override
    public String toString(){
        String a= "Producto: "+nombre+" ID: "+id+" Precio: "+precio;
        return a;                   
    }

}

In spite of having the toString method, the error does not change, nor does netbeans recognize the getters with autocompletion, so there is something wrong with me, nor is it a try-catch topic, since it should only take values already added and printed

private Productos Productos;
private ArrayList<Productos> productos = new ArrayList<>();

public void newProducto(){
    System.out.println("Ingrese nombre del producto");
    String nombre = sc.nextLine();
    System.out.println("Ingrese precio del producto");
    int precio=sc.nextInt();
    int id = productos.size()+1;
    new Productos(id, precio, nombre);
    productos.add(Productos);
}
public void mostrarProductos(){
   for(int i=0; i<productos.size();i++){
       System.out.println(productos.get(i).toString());

   }
}

Thank you very much in advance.

    
asked by Juampa57 11.12.2018 в 20:48
source

2 answers

0

Test in the toString method to change the variables by the methods that return them.

String a= "Producto: "+getNombre()+" ID: "+getId()+" Precio: "+getPrecio();

And if not then it stores the values in variables within the method (Although it would not do any good and would add incense lines).

String nombre = getNombre();
    
answered by 11.12.2018 в 21:32
0

After reading more I managed to find the error, it was the way in which the object was being stored.

Instead of being

new Productos(id, precio, nombre);
productos.add(Productos);

it must have been

Productos p = new Productos(id, precio, nombre);
productos.add(p);
    
answered by 11.12.2018 в 21:45