I have a problem with a NullPointerException when comparing a String [closed]

1

Well, in this program the idea is to register a department and then register an employee, which asks you for a department in which the employee works.

The problem is that when I put the department I made a method to compare the one with an existing one and if it exists I return a true to complete the creation of that employee but it gives me a NullPointerException and I do not know the reason or reason.

If you do not understand my request what I have to do is that the seller registered in a Hashtable and the department in an arrangement of objects let me calculate the seller's commission based on its sales amount, what I want is let me register the seller when comparing the department entered with one of the existing arrangement.

This is my code:

import java.util.*;

public class Principal {

    int op;
    int depaid;
    Departamento depo[] = new Departamento[10];
    Vendedor vn = new Vendedor();
    Scanner nc = new Scanner(System.in);
    Hashtable<Integer, Vendedor> ht = new Hashtable<Integer, Vendedor>();

    public static void main(String[] Args) {
        Principal m = new Principal();
        m.menu();
    }

    public void menu() {
        int op;
        Scanner nc = new Scanner(System.in);

        do {
            System.out.println("Que desea hacer? ");
            System.out.println("1-° Dar de alta un vendedor.");
            System.out.println("2-° Asignar el valor de ventas. ");
            System.out.println("3-° Consultar a un empleado.");
            System.out.println("4-° Consultar a todos los vendedores.");
            System.out.println("5-° Dar de alta un departamento.");
            System.out.println("6-° Calcular comsion.");
            System.out.println("7-° Salir.");
            op = nc.nextInt();

            switch (op) {
                case 1:
                    altae();
                    break;
                case 2:
                    asignar();
                    break;
                case 3:
                    buscar();
                    break;
                case 4:
                    imprime();
                    break;
                case 5:
                    altad();
                    break;
                case 6:
                    calculac();
            }
        } while (op != 7);
    }

    public void calculac() {
        String nom2;
        System.out.println("Introuduzca el nombre del empleado");
        String nom = nc.nextLine();
        nom = nom.toUpperCase();
        Enumeration<Vendedor> eht = ht.elements();

        while (eht.hasMoreElements()) {
            Vendedor ven = eht.nextElement();
            nom2 = ven.getNombre();
            if (nom.compareTo(ven.getNombre()) == 0) {
                System.out.println("Salut");
            }
        }
    }

    public void altae() {
        String dep1;

        System.out.println("Introduzca la clave del empleado");
        int cl = nc.nextInt();

        if (ht.containsKey(cl)) {
            System.out.println("La clave ya existe");
        } else {
            nc.nextLine();
            System.out.println("Introduzca el nombre del empleado");
            String nom = nc.nextLine();
            if (nom != null) {
                System.out.println("Introduzca el departamento del empleado ");
                String dep = nc.nextLine();
                if (dep != null) {
                    if (BuscaDep(dep)) {
                        System.out.println("Hola");
                        vn = new Vendedor(cl, nom.toUpperCase(), dep.toUpperCase(), 0);
                        System.out.println("Dado de alta exitosamente");
                        ht.put(cl, vn);
                    }
                } else {
                    System.out.println("El departamento no puede ser nulo");
                }
            } else {
                System.out.println("El nombre no puede ser nulo");
            }
        }
    }

    public boolean BuscaDep(String nomD) {
        boolean bandera = false;
        for (int n = 0; n < depo.length; n++) {
            if (depo[n].getNom() != null) {
                if (nomD.compareTo(depo[n].getNom()) == 0) {//No entra en este iff
                    bandera = true;
                }
            }
        }
        System.out.println(bandera);
        return bandera;
    }

    public void altad() {
        String dep;
        int cld;
        double com;
        System.out.println("Introduzca la clave del departamento");
        cld = nc.nextInt();
        nc.nextLine();
        System.out.println("Introduzca el nombre del nuevo departamento");
        dep = nc.nextLine();
        if (dep != null) {
            System.out.println("Introduzca el porcentaje de comision en decimal");
            com = nc.nextDouble();
            if (com > 0) {
                depo[depaid] = new Departamento(cld, dep.toUpperCase(), com);
                depaid++;
                System.out.println("Departamento creado exitosamente");
            }
        }
    }

    public void buscar() {
        String nom2;
        System.out.println("Introuduzca el nombre del empleado");
        String nom = nc.nextLine();
        nom = nom.toUpperCase();
        Enumeration<Vendedor> eht = ht.elements();

        while (eht.hasMoreElements()) {
            Vendedor ven = eht.nextElement();
            nom2 = ven.getNombre();
            if (nom.compareTo(ven.getNombre()) == 0) {
                System.out.println("Se encontro: " + ven);
            }
        }
    }

    public void imprime() {
        Enumeration<Integer> rht = ht.keys();
        while (rht.hasMoreElements()) {
            Integer clave = (Integer) rht.nextElement();
            System.out.println(ht.get(clave));
        }
    }

    public void asignar() {
        System.out.println("Introduzca la clave del empleado");
        int cl = nc.nextInt();
        if (ht.containsKey(cl)) {
            Vendedor ven = ht.get(cl);
            System.out.println("Cuanto desea agregar al importe de venta");
            double idv = nc.nextDouble();
            ven.setIdv(idv);
        } else {
            System.out.println("No se encontró");
            System.out.println();
        }
    }
}
public class Vendedor {

    private int clave;
    private String nombre, departamento;
    private double idv;

    public Vendedor() {
    }

    public Vendedor(int clave, String nombre, String departamento, double idv) {
        this.clave = clave;
        this.nombre = nombre;
        this.departamento = departamento;
        this.idv = idv;
    }

    public Vendedor(int clave, String nombre, String departamento) {
        this.clave = clave;
        this.nombre = nombre;
        this.departamento = departamento;
    }

    public int getClave() {
        return clave;
    }

    public void setClave(int clave) {
        this.clave = clave;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getDepartamento() {
        return departamento;
    }

    public void setDepartamento(String departamento) {
        this.departamento = departamento;
    }

    public double getIdv() {
        return idv;
    }

    public void setIdv(double idv) {
        this.idv = this.idv + idv;
    }

    @Override
    public String toString() {
        return "Vendedor [Clave del empleado: " + clave + ", Nombre=" + nombre + ", Departamento=" + departamento + ", Importe de ventas=" + idv
                + "]";
    }
}
public class Departamento {

    private int claved;
    private String nom;
    private double comision;

    public Departamento() {
    }

    public Departamento(int claved, String nom, double comision) {
        this.claved = claved;
        this.nom = nom;
        this.comision = comision;
    }

    public int getClaved() {
        return claved;
    }

    public void setClaved(int claved) {
        this.claved = claved;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public double getComision() {
        return comision;
    }

    public void setComision(double comision) {
        this.comision = comision;
    }

    @Override
    public String toString() {
        return "Departamento [Clave de departamento=" + claved + ", Nombre=" + nom + ", Porcentaje de Comision=" + comision + "]";
    }
}
    
asked by Guillermo Cruz 02.03.2017 в 02:03
source

2 answers

0

The problem is within the BuscaDep() method, trying to get the values of the department objects array, variable depo , all elements have a null value, that's why you get NullPointerException.

 public boolean BuscaDep(String nomD) {
        boolean bandera = false;
        for (int n = 0; n < depo.length; n++) {
            if (depo[n].getNom() != null) {  //*** Los elementos dentro del array tienen valor null.
                if (nomD.compareTo(depo[n].getNom()) == 0) {//No entra en este iff
                    bandera = true;
                }
            }
        }
        System.out.println(bandera);
        return bandera;
    }

To avoid looking for elements Departamento with value null, avoid calling the method BuscaDep(dep) since at that point no department has been created, when you register a seller comments the following lines:

   public void altae() {

     ...
     ...
                System.out.println("Introduzca el departamento del empleado ");
                String dep = nc.nextLine();
                if (dep != null) {
                    //if (BuscaDep(dep)) {
                        System.out.println("Hola");
                        vn = new Vendedor(cl, nom.toUpperCase(), dep.toUpperCase(), 0);
                        System.out.println("Dado de alta exitosamente");
                        ht.put(cl, vn);
                    //}
                } else {
                    System.out.println("El departamento no puede ser nulo");
         ...
         ...
    }
    
answered by 02.03.2017 в 06:38
0

This is a bit of what I managed to fix. I eliminated the Hashtable. I ordered the variables a bit, but there are still some errors: P (maybe correct them)

import java.util.*;

public class Principal {

    static final String MSG_INGRESE_COMISION_DEPARTAMENTO = "Introduzca el porcentaje de comision en decimal";
    static final String MSG_DEPARTAMENTO_CREADO = "Departamento creado exitosamente";
    static final String MSG_INGRESE_NOMBRE_DEPARTAMENTO = "Introduzca el nombre del departamento";
    static final String MSG_INGRESE_CLAVE_DEPARTAMENTO = "Introduzca la clave del departamento";
    static final String MSG_INGRESE_NOMBRE_EMPLEADO = "Introuduzca el nombre del empleado";
    static final String MSG_INGRESE_CLAVE_EMPLEADO = "Introduzca la clave del empleado";
    static final String MSG_OPCION_INVALIDA = "Ingese una opcion válida.";
    static final String MSG_OPCIONES_MENU = "Que desea hacer?\n1-° Dar de alta un vendedor.\n"
            + "2-° Asignar el valor de ventas.\n3-° Consultar a un empleado.\n4-° Consultar a "
            + "todos los vendedores.\n5-° Dar de alta un departamento.\n6-° Calcular comsion.\n"
            + "7-° Salir.";

    ArrayList<Departamento> departamentos = new ArrayList<>();
    ArrayList<Vendedor> vendedores = new ArrayList<>();

    Scanner scan = new Scanner(System.in);

    public static void main(String[] Args) {
        Principal m = new Principal();
        m.ImprimirMenu();
    }

    public void ImprimirMenu() {
        int opcion;

        do {
            System.out.println(MSG_OPCIONES_MENU);

            try {
                opcion = scan.nextInt();
            } catch (InputMismatchException e) {
                opcion = -1;
            }
            switch (opcion) {
                case 1:
                    crearVendedor();
                    break;
                case 2:
                    asignarVentas();
                    break;
                case 3:
                    buscarEmpleado();
                    break;
                case 4:
                    imprimeVendedores();
                    break;
                case 5:
                    crearDepartemento();
                    break;
                case 6:
                    calculaComision();
                default:
                    System.out.println(MSG_OPCION_INVALIDA);
            }
        } while (opcion > 0 || opcion < 8);
    }

    public void calculaComision() {

    }

    public void crearVendedor() {
        int dep, claveVendedor;
        String nombreVendedor = null;

        do {
            System.out.println(MSG_INGRESE_CLAVE_EMPLEADO);
            try {
                claveVendedor = scan.nextInt();
                if (indiceVendedor(claveVendedor) != -1) {
                    System.out.println("La clave ya existe");
                    claveVendedor = -1;
                }
            } catch (InputMismatchException e) {
                claveVendedor = -1;
            }
        } while (claveVendedor <= 0);

        do {
            System.out.println(MSG_INGRESE_NOMBRE_EMPLEADO);
            nombreVendedor = scan.nextLine();
        } while (nombreVendedor == null || nombreVendedor.trim().length() <= 0);

        do {
            System.out.println("Introduzca el departamento del empleado ");
            dep = scan.nextInt();

        } while (dep < 0);

        vendedores.add(new Vendedor(claveVendedor, nombreVendedor.toUpperCase(), dep, 0));
        System.out.println("Dado de alta exitosamente");
    }

    public boolean existeDepartamento(int clave) {
        for (Departamento dept : departamentos) {
            if (clave == dept.getClave()) {
                return true;
            }
        }

        return false;
    }

    public void crearDepartemento() {
        int claveDept;
        double comisionDept;
        String nombreDept = null;

        do {
            System.out.println(MSG_INGRESE_CLAVE_DEPARTAMENTO);
            try {
                claveDept = scan.nextInt();

            } catch (InputMismatchException e) {
                claveDept = -1;
            }
        } while (claveDept > 0);

        do {
            System.out.println(MSG_INGRESE_NOMBRE_DEPARTAMENTO);
            nombreDept = scan.nextLine();
        } while (nombreDept != null && nombreDept.trim().length() > 0);

        do {
            System.out.println(MSG_INGRESE_COMISION_DEPARTAMENTO);
            try {
                comisionDept = scan.nextDouble();
            } catch (InputMismatchException e) {
                comisionDept = -1;
            }
        } while (comisionDept > 0);

        departamentos.add(new Departamento(claveDept, nombreDept.toUpperCase(), comisionDept));
        System.out.println(MSG_DEPARTAMENTO_CREADO);
    }

    public void buscarEmpleado() {
        String nombreVendedor;
        System.out.println(MSG_INGRESE_NOMBRE_EMPLEADO);

        do {
            System.out.println(MSG_INGRESE_NOMBRE_DEPARTAMENTO);
            nombreVendedor = scan.nextLine();
        } while (nombreVendedor != null && nombreVendedor.trim().length() > 0);

        int indice = indiceVendedor(nombreVendedor);

        if (indice >= 0) {
            System.out.println("Se encontró " + vendedores.get(indice));
        } else {
            System.out.println("No se encontró");
        }
    }

    public int indiceVendedor(String nombre) {
        for (int i = 0; i < vendedores.size(); i++) {
            if (nombre.equals(vendedores.get(i).getNombre())) {
                return i;
            }
        }

        return -1;
    }

    public int indiceVendedor(int clave) {
        for (int i = 0; i < vendedores.size(); i++) {
            if (clave == vendedores.get(i).getClave()) {
                return i;
            }
        }

        return -1;
    }

    public void imprimeVendedores() {
        for (Vendedor vend : vendedores) {
            System.out.println(vend);
        }
    }

    public void asignarVentas() {

    }
}
    
answered by 02.03.2017 в 07:11