Print data belonging to a TreeMap

2

In the consultas() method, how could you print the student's name and grades?

Until now, what it prints are memory addresses, and not the name and qualifications.

Note: The map that receives this method is a map that returns a method called darDeAlta() which receives the data of a new student.

class Alumno {

private String nombre;
private int matricula;
private double calificaciones[];



Alumno(String nombre, int matricula, double calificaciones[]) {

    this.calificaciones = calificaciones;

}

String getNombre() {
    return nombre;
}

int getMat() {
    return matricula;
}

double[] getCalif() {
    return calificaciones;
}

void setCalif(double calif[]) {
    calificaciones = calif;
}

}
public class Ejercicio {

Map<Integer, Alumno> alumnos = new TreeMap<>();  
  public Map darDeAlta() {
    Scanner y = new Scanner(System.in);
    //boolean b=false;

    double d[] = new double[5];

    System.out.println("Introduzca el nombre del estudiante");
    String n = y.nextLine();
    System.out.println("Introduzca su matricula (de 5 digitos)");
    int m = y.nextInt();
    System.out.println("Introduzca las calificaciones: \n");
    for (int i = 0; i < 5; i++) {
        System.out.println("Introduzca la calificacion");
        d[i] = y.nextDouble();

    }

    if (alumnos.containsKey(m)) {
        System.out.println("Esa matricula ya existe, ingrese otra matricula");

    } else {
        alumnos.put(m, new Alumno(n, m, d));
        System.out.println("Se han dado de alta los datos :)");
        System.out.println("Desea ingresar mas alumnos? \n");


        String s = y.next();
        //if (s.compareTo("si")==0 || s.compareTo("no")==0) 
           // b = true;


    }

    return alumnos;

}

 public boolean consultas(Map alumnos) {
    Scanner y = new Scanner(System.in);
    boolean c;

    System.out.println("Introduzca la matricula del estudiante a buscar");
    int k = y.nextInt();
    c = alumnos.containsKey(k);
    if (c) {

        System.out.println("Los datos son:\n" +"Nombre del alumno: "+ alumnos.get(k) + "Calificaciones: " + alumnos.values());
        //System.out.println("Los datos son:\n" +"Nombre del alumno: "+ alumnos.get(k).getNombre() + "Calificaciones: " + al.getCalif());
    } else {
        System.out.println("El alumno no se encuentra");
    }
return true;
}
    
asked by Michelle 27.09.2017 в 01:20
source

2 answers

3

In your code you have several errors.

First

In your class Alumno you are only initializing the variable calificaciones , so you can only access information stored in that variable. If you try to access any other variable through the get methods, you will not get anything, since you are not assigning any type of value to it. The values that you pass to the constructor of the Student class, remain in nothingness, except for the value of the parameter calificaciones , since that you pass it to the variable calificaciones .

To assign values to the other variables, you have to initialize them in the constructor.

Alumno(String nombre, int matricula, double calificaciones[]) {

    this.nombre = nombre;
    this.matricula = matricula;
    this.calificaciones = calificaciones;

}

Second

To obtain the values stored in the variables of the class Alumno , you have to access the method get of the variables, otherwise you will only access the object Student and show you "memory addresses", as you is happening To avoid that you would have to overwrite the toString() method and within the return a String in which you concatenate the value of all the variables.

To access the values of the variables, use the get methods of these.

// con getNombre() obtienes el valor almacenado en la variable nombre.
alumnos.get(k).getNombre()

With alumnos.get(k) you access the object of type Student, so that this is shown as a String overwrites the method toString() .

public String toString() {

    String alumno = "nombre: " +this.nombre+ 
                    ", matricula: " +this.matricula+ 
                    ", calificaciones: " +Arrays.toString(this.calificaciones)+ "";
    return alumno;
}

With these corrections your code would look like this:

Student

class Alumno {

    private String nombre;
    private int matricula;
    private double calificaciones[];

    Alumno(String nombre, int matricula, double calificaciones[]) {

        // inicializas los valores de todas las variables
        this.nombre = nombre;
        this.matricula = matricula;
        this.calificaciones = calificaciones;
    }

    String getNombre() {
        return nombre;
    }

    int getMat() {
        return matricula;
    }

    double[] getCalif() {
        return calificaciones;
    }

    void setCalif(double calif[]) {
        calificaciones = calif;
    }

    // Sobrescribes el metodo toString() y retornas un String con los 
    // valores de las variables concatenados. 
    public String toString() {

        String alumno = "nombre: " +this.nombre+ 
                        ", matricula: " +this.matricula+ 
                        ", calificaciones: " +Arrays.toString(this.calificaciones)+ "";
        return alumno;
    }

}

Exercise

public class Ejercicio {

    Map<Integer, Alumno> alumnos = new TreeMap<>(); 

    public Map darDeAlta() {
        Scanner y = new Scanner(System.in);
        //boolean b=false;

        double d[] = new double[5];

        System.out.println("Introduzca el nombre del estudiante");
        String n = y.nextLine();
        System.out.println("Introduzca su matricula (de 5 digitos)");
        int m = y.nextInt();
        System.out.println("Introduzca las calificaciones: \n");
        for (int i = 0; i < 5; i++) {
            System.out.println("Introduzca la calificacion");
            d[i] = y.nextDouble();
        }

        if (alumnos.containsKey(m)) {
            System.out.println("Esa matricula ya existe, ingrese otra matricula");
        } else {
            alumnos.put(m, new Alumno(n, m, d));
            System.out.println("Se han dado de alta los datos :)");
            System.out.println("Desea ingresar mas alumnos? \n");

            String s = y.next();
            //if (s.compareTo("si")==0 || s.compareTo("no")==0) 
               // b = true;
        }

        return alumnos;
    }

    public boolean consultas(Map alumnos) {

        Scanner y = new Scanner(System.in);
        boolean c;

        System.out.println("Introduzca la matricula del estudiante a buscar");
        int k = y.nextInt();
        c = alumnos.containsKey(k);
        if (c) {

            // Muestras los datos de los alumnos obteniendo el valor de las variables
            System.out.println("Los datos son:\n" 
                +"Nombre del alumno: "+ alumnos.get(k).getNombre() 
                +"Calificaciones: " + alumnos.get(k).getCalif());

            // Muestras todos los datos de los alumnos.
            // Recuerda que con 'alumnos.get(k)' estas accediendo al objeto alumno y
            // al sobreescribir el metodo 'toString()' en la clase Alumnos obtienes 
            // los datos que retornas en el metodo 'toString()'
            System.out.println("Los datos son:\n" +alumnos.get(k));

        } else {
            System.out.println("El alumno no se encuentra");
        }

        return true;
    }
}
    
answered by 27.09.2017 / 02:49
source
1

Your class Alumno is missing assigning the values of nombre and matricula in the constructor.

Also, you can or should add a toString() method to your student class to be able to read the map.

Notice that the map reading shows you the data as you have defined the toString .

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.util.Arrays;

/**
 *
 * @author cedano
 */
class Alumno {

private String nombre;
private int matricula;
private double calificaciones[];



Alumno(String nombre, int matricula, double calificaciones[]) {

    this.calificaciones = calificaciones;
    this.nombre = nombre;
    this.matricula = matricula;

}

String getNombre() {
    return nombre;
}

int getMat() {
    return matricula;
}

double[] getCalif() {
    return calificaciones;
}

void setCalif(double calif[]) {
    calificaciones = calif;
}

public String toString(){
     //return super.toString();
     return "("+this.nombre+":"+this.matricula+":"+Arrays.toString(this.calificaciones)+")";
    }


}

Then you can read the map like this:

for (Map.Entry<Integer, Alumno> entry : alumnos.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());
  }

You'll have something like this:

KEY : 1      VALUE : (Pedro:1:[10.2, 2.3, 3.6, 4.6])
KEY : 2      VALUE : (Santiago:2:[9.2, 4.5, 10.3, 9.5])

If you do not want to implement the toString method, you can do it this way:

for (Map.Entry<Integer, Alumno> entry : alumnos.entrySet()) {
    String strDatos=  "Nombre:"+entry.getValue().getNombre()
                    + " - Matricula: "+entry.getValue().getMat()
                    + " - Calificaciones:"+Arrays.toString(entry.getValue().getCalif());
   System.out.println(strDatos);
  }

The result will be:

Nombre:Pedro - Matricula: 1 - Calificaciones:[10.2, 2.3, 3.6, 4.6]
Nombre:Santiago - Matricula: 2 - Calificaciones:[9.2, 4.5, 10.3, 9.5]

P.D .: As of Java 8, the maps read like this:

   alumnos.entrySet().stream().map((entry) -> "Nombre:"+entry.getValue().getNombre()
           + " - Matricula: "+entry.getValue().getMat()
           + " - Calificaciones:"+Arrays.toString(entry.getValue().getCalif())).forEachOrdered((strDatos) -> {
               System.out.println(strDatos);
});

To print a specific student

Questions for the key of the student using containsKey(keyDelAlumno) , for example, if you want the data of Student 1:

int intUnAlumno=1;
if (alumnos.containsKey(intUnAlumno)) {
    Object esteAlumno = alumnos.get(intUnAlumno);
    System.out.println("Alumno (datos como están en toString) : " + esteAlumno);
 }

Result:

Alumno (datos como están en toString) : (Pedro:1:[10.2, 2.3, 3.6, 4.6])
    
answered by 27.09.2017 в 02:04