Get value from a HashMap

1

Hi, I am doing an exercise in java for classes and I am not able to make the method consult the Department method. In the class where I have the main, I have made a menu where I ask for the number of the department that is in the Employee class. All the time I get the message that the department does not exist when it does exist since I am making a connection to a database. In a part of the main menu I have this.

public interface Constantes {
String NOMBRE_SOCIEDAD = "Editex, S.A.";
Calendar FECHA_LIQUIDACION = new GregorianCalendar(2018, 5, 15);
double SALARIO_BASE = 735.90;
Calendar FECHA_CONVENIO = new GregorianCalendar(1985, 0, 1);

}

public abstract class Empleado {

private int numeroEmpleado;
private String nombreEmpleado;
private Calendar fechaIngreso;
private double salario;
private double comision;
private int porcentaje;
private Departamento departamento;
private int numcat;

public Empleado(int numeroEmpleado, String nombreEmpleado, Calendar fechaIngreso, double salario, double comision, Departamento departamento, int numcat) throws FechaIngresoFueraConvenio {
    this.numeroEmpleado = numeroEmpleado;
    this.nombreEmpleado = nombreEmpleado;
    setFechaIngreso(fechaIngreso);
    setSalario(salario);
    setComision(comision);
    this.departamento = departamento;
    this.numcat = numcat;
    setPorcentaje();
}

/**
 * @return the numeroEmpleado
 */
public int getNumeroEmpleado() {
    return numeroEmpleado;
}

/**
 * @return the nombreEmpleado
 */
public String getNombreEmpleado() {
    return nombreEmpleado;
}

/**
 * @return the fechaIngreso
 */
public Calendar getFechaIngreso() {
    return fechaIngreso;
}

/**
 * @return the salario
 */
public double getSalario() {
    return salario;
}

/**
 * @return the comision
 */
public double getComision() {
    return comision;
}

/**
 * @return the porcentaje
 */
public int getPorcentaje() {
    return porcentaje;
}

/**
 * @return the departamento
 */
public Departamento getDepartamento() {
    return departamento;
}

/**
 * @return the numcat
 */
public int getNumcat() {
    return numcat;
}

/**
 * @param numeroEmpleado the numeroEmpleado to set
 */
public void setNumeroEmpleado(int numeroEmpleado) {
    this.numeroEmpleado = numeroEmpleado;
}

/**
 * @param nombreEmpleado the nombreEmpleado to set
 */
public void setNombreEmpleado(String nombreEmpleado) {
    this.nombreEmpleado = nombreEmpleado;
}

/**
 * @param fechaIngreso the fechaIngreso to set
 */
public void setFechaIngreso(Calendar fechaIngreso) throws FechaIngresoFueraConvenio {
    if (fechaIngreso.compareTo(Constantes.FECHA_CONVENIO) >= 0) {
        this.fechaIngreso = fechaIngreso;
    } else {
        throw new FechaIngresoFueraConvenio("El empleado núm:" + getNumeroEmpleado() + ", " + getNombreEmpleado() + " tiene una fecha de ingreso, fuera de convenio: " + fechaIngreso.get(Calendar.YEAR));
    }
}

/**
 * @param salario the salario to set
 */
public void setSalario(double salario) {

    if (salario < Constantes.SALARIO_BASE) {
        salario = Constantes.SALARIO_BASE;
    } else {
        this.salario = salario;
    }
}

/**
 * @param comision the comision to set
 */
public void setComision(double comision) {

    if (comision > getSalario()) {
        comision = getSalario();
    } else {
        this.comision = comision;
    }
}

/**
 * @param porcentaje the porcentaje to set
 */
public void setPorcentaje() {
    int anio = (int) Math.floor((Constantes.FECHA_LIQUIDACION.getTimeInMillis() - fechaIngreso.getTimeInMillis()) / (1000 * 60 * 60 * 24 * 365.25));
    this.porcentaje = anio;
}

/**
 * @param departamento the departamento to set
 */
public void setDepartamento(Departamento departamento) {
    this.departamento = departamento;
}

/**
 * @param numcat the numcat to set
 */
public void setNumcat(int numcat) {
    this.numcat = numcat;
}

public double calcularLiquidacion() {
    double total = (getSalario() + getComision()) * (getPorcentaje() / 100.0);
    return total;
}

public String toString() {
    return String.format("Núm %2d %-18s %-45s", getNumeroEmpleado(), getNombreEmpleado(), getDepartamento().toString());
}

}

public class EmpleadoBase extends Empleado {

private double pagas;

public EmpleadoBase(int numeroEmpleado, String nombreEmpleado, Calendar fechaIngreso, double salario, double comision, Departamento departamento, int numcat, double pagas) throws FechaIngresoFueraConvenio {
    super(numeroEmpleado, nombreEmpleado, fechaIngreso, salario, comision, departamento, numcat);
    this.pagas = pagas;
}

public double calcularLiquidacion() {
    double total = pagas + super.calcularLiquidacion();
    return total;
}

public String toString() {
    return "EMPLEADO BASE " + super.toString() + " LIQUIDACIÓN " + this.calcularLiquidacion() + "\n";
}

}

public class Comercial extends Empleado{
 private double pagas;

public Comercial(int numeroEmpleado, String nombreEmpleado, Calendar fechaIngreso, double salario, double comision, Departamento departamento, int numcat, double pagas) throws FechaIngresoFueraConvenio {
    super(numeroEmpleado, nombreEmpleado, fechaIngreso, salario, comision, departamento, numcat);
    this.pagas = pagas;
}

public double calcularLiquidacion(){
    double total = pagas+super.calcularLiquidacion();
    return total;
}

public String toString(){
    //return "EMPLEADO BASE " + super.toString()+ " LIQUIDACIÓN " + this.calcularLiquidacion()+"\n";
    return String.format("COMERCIAL %-18s LIQUIDACION %2s\n", super.toString(), this.calcularLiquidacion());
}

}

public class Directivo extends Empleado {

private double pagas;
private double plusDireccion;

public Directivo(int numeroEmpleado, String nombreEmpleado, Calendar fechaIngreso, double salario, double comision, Departamento departamento, int numcat, double pagas) throws FechaIngresoFueraConvenio {
    super(numeroEmpleado, nombreEmpleado, fechaIngreso, salario, comision, departamento, numcat);
    this.pagas = pagas;
    setPlusDireccion();
}

public void setPlusDireccion() {
    plusDireccion = (getComision() + getSalario()) * 0.25;
}

public double calcularLiquidacion() {
    double total = pagas + super.calcularLiquidacion() + plusDireccion;
    return total;
}

public String toString() {
    return "DIRECTIVO " + super.toString() + " LIQUIDACIÓN " + this.calcularLiquidacion() + "\n";
}

}

public class Ejecutivo extends Empleado {

private double pagas;

public Ejecutivo(int numeroEmpleado, String nombreEmpleado, Calendar fechaIngreso, double salario, double comision, Departamento departamento, int numcat, double pagas) throws FechaIngresoFueraConvenio {
    super(numeroEmpleado, nombreEmpleado, fechaIngreso, salario, comision, departamento, numcat);
    this.pagas = pagas;
}

public double calcularLiquidacion() {
    double total = pagas + super.calcularLiquidacion();
    return total;
}

public String toString() {
    return "EJECUTIVO " + super.toString() + " LIQUIDACION: " + this.calcularLiquidacion() + "\n";
}

}

public class Tecnico extends Empleado {

private double pagas;
private String tipoTecnico;

public Tecnico(int numeroEmpleado, String nombreEmpleado, Calendar fechaIngreso, double salario, double comision, Departamento departamento, int numcat, double pagas) throws FechaIngresoFueraConvenio {
    super(numeroEmpleado, nombreEmpleado, fechaIngreso, salario, comision, departamento, numcat);
    this.pagas = pagas;
    setTipoTecnico();
}

/**
 * @param tipoTecnico the tipoTecnico to set
 */
public void setTipoTecnico() {
    if (super.getNumcat() == 2) {
        tipoTecnico = "AUXILIAR";
    } else if (getNumcat() == 3) {
        tipoTecnico = "ESPECIALISTA";
    }
}

public double calcularLiquidacion() {
    double total = pagas + super.calcularLiquidacion();
    return total;
}

public String toString() {
    return "TECNICO " + tipoTecnico + " " + super.toString() + " LIQUIDACION: " + this.calcularLiquidacion() + "\n";
}

}

public class Departamento {
private int numeroDepartamento;
private String nombreDepto;
private String nombreCentro;

public Departamento(int numeroDepartamento, String nombreDepto, String nombreCentro) {
    this.numeroDepartamento = numeroDepartamento;
    this.nombreDepto = nombreDepto;
    this.nombreCentro = nombreCentro;
}

public int getNumeroDepartamento() {
    return numeroDepartamento;
}

public void setNumeroDepartamento(int numeroDepartamento) {
    this.numeroDepartamento = numeroDepartamento;
}

public String getNombreDepto() {
    return nombreDepto;
}

public void setNombreDepto(String nombreDepto) {
    this.nombreDepto = nombreDepto;
}

public String getNombreCentro() {
    return nombreCentro;
}

public void setNombreCentro(String nombreCentro) {
    this.nombreCentro = nombreCentro;
}

@Override
public String toString() {
    return "[" + nombreDepto + "(" + nombreCentro+")" + ']';
}

}

public class FechaIngresoFueraConvenio extends Exception{
public FechaIngresoFueraConvenio(String msg){
    super(msg);
}

}

public class Liquidacion {

private HashMap<Integer, Empleado> plantilla = new HashMap<Integer, Empleado>();

public void insertaEmpleado(int numero, Empleado empleado) {
    plantilla.put(numero, empleado);
}

public String consultaEmpleado(int numero) {
    String mensaje = "";
    double acumulador = 0.0;//acumular la liquidacion
    boolean encontrado = false;

    Set<Integer> numeros = plantilla.keySet();
    Iterator<Integer> it = numeros.iterator();

    while (it.hasNext()) {
        Integer num = it.next();
        if (plantilla.get(num).getNumeroEmpleado() == numero) {
            acumulador += plantilla.get(num).calcularLiquidacion();
            mensaje += plantilla.get(num).toString();
            encontrado = true;
        }
    }

    if (encontrado) {
        return mensaje;
    } else {
        return String.format("No existe el empleado o está fuera del convenio");
    }

}

public String consultaDepartamento(int numero) {
    String mensaje = "LIQUIDACION POR DEPARTAMENTO\n";
    double acumulador = 0.0;//acumular la liquidacion
    boolean encontrado = false;

    Set<Integer> numeros = plantilla.keySet();
    Iterator<Integer> it = numeros.iterator();
    while (it.hasNext()) {
        Integer num = it.next();
        if (plantilla.get(num).getDepartamento().getNumeroDepartamento() == numero) {
            acumulador += plantilla.get(num).calcularLiquidacion();
            mensaje += plantilla.get(num).toString();
            encontrado = true;
        }
        //System.out.println("debug: "+plantilla.get(num).getDepartamento().getNumeroDepartamento());
    }


    if(encontrado){
        return mensaje.toString() +"\nTOTAL:"+acumulador+"\nFIN DE LISTADO DEPARTAMENTO";
    } else{
        return null;
    }
}

public String consultaPlantilla() {
    String listadoPlantilla = null;
    Double acumulador = 0.0;
    listadoPlantilla = "LIQUIDACION: Editex, S.A.\n";
    Set<Integer> numeros = plantilla.keySet();
    Iterator<Integer> it = numeros.iterator();
    while (it.hasNext()) {
        Integer num = it.next();
        acumulador += plantilla.get(num).calcularLiquidacion();
        listadoPlantilla += plantilla.get(num).toString() + "\n";
    }

    return listadoPlantilla += "\t\t\t\t\t\t\t\t\tTOTAL EMPRESA: " + acumulador + "\n" + "****FIN LISTADO EMPRESA****";
}

}

--------------- MAIN -------------------

public class Aplicacion {

static Empleado empleado = null;
static Liquidacion liquidacion = new Liquidacion();
static Departamento departamento = null;
static Date fechin;
static Calendar fechaIngreso = Calendar.getInstance();

public static void main(String[] args) {
    Connection conexion = null;
    //Creamos un objeto de tipo Statement
    PreparedStatement stm = null;
    ResultSet rset = null;

    try {
        Class.forName("oracle.jdbc.OracleDriver");
        // Base de datos a la que vamos a conectar
        String BaseDeDatos = "jdbc:oracle:thin:@localhost:1521:xe";
        // Establecer la conexión
        conexion = DriverManager.getConnection(BaseDeDatos, "DAW1", "DAW1");

        //CONSULTA
        stm = conexion.prepareStatement("select e.numemple, e.nomemple, e.fechin, e.salario, e.comision, p.julio, p.navidad, c.nomce, d.numdepto, d.nomdepto, p.numcat "
                + "from empleado e, paga p, departamento d, centro c "
                + "where e.numcat=p.numcat and d.numce = c.numce");
        rset = stm.executeQuery();

        while (rset.next()) {
            fechin = rset.getDate(3);
            fechaIngreso.setTime(fechin);
            double pagas = (rset.getDouble(6) + rset.getDouble(7)) / 2;
            departamento = new Departamento(rset.getInt(9), rset.getString(10), rset.getString(8));

            try {
                if (rset.getInt(11) == 1) {
                    empleado = new EmpleadoBase(rset.getInt(1), rset.getString(2), fechaIngreso, rset.getDouble(4), rset.getDouble(5), departamento, rset.getInt(11), pagas);
                }
                if (rset.getInt(11) == 2 || rset.getInt(11) == 3) {
                    empleado = new Tecnico(rset.getInt(1), rset.getString(2), fechaIngreso, rset.getDouble(4), rset.getDouble(5), departamento, rset.getInt(11), pagas);
                }
                if (rset.getInt(11) == 4 || rset.getInt(11) == 5) {
                    empleado = new Ejecutivo(rset.getInt(1), rset.getString(2), fechaIngreso, rset.getDouble(4), rset.getDouble(5), departamento, rset.getInt(11), pagas);
                }
                if (rset.getInt(11) == 6) {
                    empleado = new Comercial(rset.getInt(1), rset.getString(2), fechaIngreso, rset.getDouble(4), rset.getDouble(5), departamento, rset.getInt(11), pagas);
                }
                if (rset.getInt(11) == 7) {
                    empleado = new Directivo(rset.getInt(1), rset.getString(2), fechaIngreso, rset.getDouble(4), rset.getDouble(5), departamento, rset.getInt(11), pagas);
                }
            } catch (FechaIngresoFueraConvenio e) {
            }

            liquidacion.insertaEmpleado(rset.getInt(1), empleado);

        }

        Menu();
    } catch (SQLException e) {
    } catch (ClassNotFoundException e) {
    } finally {
        try {
            conexion.close();
            stm.close();
            rset.close();
        } catch (SQLException e) {
        }
    }
}

private static void Menu() {
    int opcion = 0;
    Scanner entrada = new Scanner(System.in);

    do {

        System.out.println("Editex, S.A. Consulta liquidaciones:\n"
                + "1. Empleado\n"
                + "2. Departamento\n"
                + "3. Plantilla\n"
                + "4. Salir\n"
                + "Elige la opción (1/2/3/4).");
        opcion = entrada.nextInt();
        switch (opcion) {
            case 1:
                System.out.println("Inserte el número del empleado");
                int numero = entrada.nextInt();

                System.out.println(liquidacion.consultaEmpleado(numero));
                break;
            case 2:
                System.out.println("Inserte el número de departamento");
                int numeroDepto = entrada.nextInt();

                System.out.println(liquidacion.consultaDepartamento(numeroDepto));
                break;
            case 3:
                System.out.println(liquidacion.consultaPlantilla());
                break;
            case 4:
                System.out.println("Has salido de la apliacion");
                break;
            default:
                System.out.println("Opción incorrecta");
        }
    } while (opcion != 4);
}

}

    
asked by Paco 18.06.2018 в 00:02
source

1 answer

1

I think you have a concept error with the HashMap, seeing your code when executing plantilla.put(numero, empleado); for example:

plantilla.put(1, a)
plantilla.put(1, b)
plantilla.put(2, c)
plantilla.put(2, d)
plantilla.put(2, e)

Supposedly it would have a staff of 5 employees where for department 1 it would have a, b and for 2 it would have c, d, e.

But it is not like that, your result will be only a staff of two employees on b, e. Since they are the last elements and when doing plantilla.put(2, e) machacas the employee that existed previously for that key "2" for the new one (e).

I pass you a simple code where you can see how I work with the HashMap the way you expect me to do it.

Where the key of the subject is: HashMap<Integer, List<Empleado>> plantilla = new HashMap<Integer, List<Empleado>>(); in this way you have a list of employees by department that is what interests you.

public class Borrar {

    public static void main(String[] args) {

        //Se crea la estructura Plantilla que tiene departamentos y listado de empleados por departamento
        HashMap<Integer, List<Empleado>> plantilla = new HashMap<Integer, List<Empleado>>();

        //Variable Para nombrar a los empleados: Empleado-1, Empleado-2...
        int empleadosCreados = 1; 

        // Inicialización de la PLANTILLA
        // Creo 3 Departamentos
        for (int i = 0; i < 3; i++) {

            // A cada departamento le añado 4 empleados
            List<Empleado> empleados= new ArrayList<Empleado>();
            for (int j = 0; j < 4; j++) {

                Empleado e = new Empleado();
                e.setNombre("Empleado-" + empleadosCreados);
                empleadosCreados++;
                empleados.add(e);
            }
            plantilla.put(i, empleados);
        }

        // En este punto tengo 3 departamentos de 4 empleados con una plantilla total de 12

        //Plantilla
        for (Entry<Integer, List<Empleado>> entry : plantilla.entrySet()) {
            List<Empleado> empleadosPorDepartamento = entry.getValue();
            for (Empleado empleado : empleadosPorDepartamento) {
                System.out.println(empleado.getNombre());
            }
        }

        //Departamento del departamento 1
        List<Empleado> empleadosPorDepartamento= plantilla.get(1);
        for (Empleado empleado : empleadosPorDepartamento) {
            System.out.println(empleado.getNombre());
        }

    }

Result:

Plantilla completa:
Empleado-1
Empleado-2
Empleado-3
Empleado-4
Empleado-5
Empleado-6
Empleado-7
Empleado-8
Empleado-9
Empleado-10
Empleado-11
Empleado-12
Empleados del departamento 1: 
Empleado-5
Empleado-6
Empleado-7
Empleado-8
    
answered by 18.06.2018 в 13:59