Error: java.lang.NullPointerException

1

I am a beginner in Java and I have a question on the subject of records. I am carrying out an article management program that allows, among other things, to register an article. The maximum number of articles that can be is 100 . They ask us the code of the article and if an article with that code already exists, it can not be registered. Then I write what I have done thanks to the help of this forum:

public class Main {

public static void main(String[] args) {

    final int MAXARTICULOS = 100; // {número de artículos máximos de la ferretería}

    class Articulo implements Serializable {

        String codart; // {código del articulo}
        String nombre; // {nombre del artículo}
        String caracteristicas; // {características}
        double precio; // {precio del artículo}
        int cantidad; // {cantidad de artículos en stock}
    }

    Articulo[] misArticulos = new Articulo[MAXARTICULOS]; // {array que contiene los artículos}
    Scanner entrada = new Scanner(System.in);
    int menu;

    System.out.println("FERRETERIA");

    for (int i = 0; i < misArticulos.length; i++) {
        System.out.println("Introduce el código: ");
        String codigo = entrada.nextLine();
        boolean encontrado = false;
        for (int j = 0; !encontrado && j < i - 1; j++) {
            if (misArticulos[j].codart.equals(codigo)) {
                System.out.println("Articulo existente");
                encontrado = true;
            }
        }

        if (!encontrado) {
            System.out.println("Introduce el nombre: ");
            misArticulos[i].nombre = entrada.nextLine();
            System.out.println("Introduce las características: ");
            misArticulos[i].caracteristicas = entrada.nextLine();
            System.out.println("Introduce el precio: ");
            misArticulos[i].precio = entrada.nextDouble();
            System.out.println("Introduce la cantidad: ");
            misArticulos[i].cantidad = entrada.nextInt();
            entrada.nextLine();
        }
    }

} // fin main

Once detected that the article does not exist, you must enter the name, the characteristics, the price and the quantity but when executing it it only lets me enter the name and then the exception java.lang.NullPointerException skips.

    
asked by Edu 03.01.2017 в 18:24
source

2 answers

0

The problem for which an exception NullPointerException is due is that you are going through the search until the end of a array that you have not yet filled in at all. You should have a variable int in which you keep the account of the items you have and perform the search from 0 to that variable.

On the other hand, if you look at the nested for loops you are iterating over the same variable i, restarting it zero again and again. This will cause the second iteration of the main loop not to enter because the i is already worth myArticles.length (). To do this you must use another second variable j as follows:

    for(int i = 0; i < misArticulos.length(); i++){
        System.out.println("Introduce el código: ");
        String codigo = entrada.nextLine();
        boolean encontrado = false;
        //buscas hasta que lo encuentras o hasta que llegas al numero de elementos actual
        for (int j = 0; !encontrado && j < i - 1; j++){
            if (misArticulos[j].codart.equals(codigo)){
                System.out.println("Articulo existent");
                encontrado = true;
            }
        }
        if (!encontrado)
            //pides los datos y los metes en misArticulos[i]
    }

There are data structures like HashMap that has methods to check if a given data already exists without having to go through the whole structure but if you are a beginner in java I recommend using a array . If you are interested you can know more in this link: link

    
answered by 03.01.2017 / 19:48
source
0

The idea is that you first go through the array, and look if it exists, before doing anything else, such that:

boolean encontrado = false;
System.out.println("Introduce el código: ");
String code = entrada.nextLine();
for (int i = 0; i < misArticulos.length; i++) {
   if ((misArticulos[i].codart).equalsIgnoreCase(code)) {
     System.out.println("El código ya existe");
     encontrado = true;
  }
}

if (!encontrado) {
  //Dar de alta
}

If the Boolean encontrado is set to false, it does not exist, therefore you would have to register there.

PS: If the property codart of your object Articulo is a Integer , or something other than String , you should make a parse, since the equalsIgnoreCase method is only valid for compare chains.

    
answered by 03.01.2017 в 18:57