Display data from a LinkedList Java class

2

Good, I have a problem when collecting the data of a class, and display them in a linked list. When the method showMiLista (LinkedList list) is executed, it returns an output in the format People @ 28d93b30 Thanks.

Biografias.java

package Ejercicio5;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

/**
 *
 * @author nando
 */
public class Biografias { 

    public static Personas cargarContactoNuevo(LinkedList list){

         Scanner entrada = new Scanner(System.in);

         System.out.println("Introduzca nombre y apellidos:");
         String nombre = entrada.nextLine();
         System.out.println("Introduzca el año de nacimiento:");
         int añoNac = entrada.nextInt();
         System.out.println("Introduzca el año de defunción:");
         int añoDef = entrada.nextInt();
         System.out.println("Introduzca área de trabajo:");
         String areaTrabajo = entrada.next();
         Personas nuevo = new Personas(nombre,añoNac,añoDef,areaTrabajo);
         list.add(nuevo);

         return nuevo;
     }

    public static void mostrarMiLista(LinkedList list){

        if(list.isEmpty()){
            System.out.println("La lista está vacia");
            return;
        }

        Iterator it = list.iterator();

         System.out.println("Los elementos de la lista son:");
         while(it.hasNext())
         {
           System.out.println(it.next().toString());
         }
}
      /**
 * Devuelve el contenido de la lista en un String
 * @return contenido de la lista
 */
@Override
public String toString(){

    String contenido="";
    Personas aux = null;

    while(aux!=null){
        contenido+=aux.getNombre()+ "\n" + aux.getAñoNac()+ "\n" + aux.getAñoDef()+ "\n" + aux.getAreaTrabajo(); //guardamos el dato

    }

    return contenido;
}

    public static void main(String[] args){
    LinkedList miLista = new LinkedList();
    Biografias bio = new Biografias();
    Scanner entrada = new Scanner (System.in);    
    int opcion;
    do{
            do{
            System.out.println("Elegir opción");
            System.out.println("1. Crear ficha de contacto");
            System.out.println("2. Mostrar contactos");
            System.out.println("3. Salir");
            opcion = entrada.nextInt();
        }while (opcion < 1 || opcion >3);

            switch(opcion){
                case 1:
                    System.out.println("Introducir datos");
                    cargarContactoNuevo(miLista);
                    break;

                case 2:
                    mostrarMiLista(miLista);
                    break;

                case 3:
                    System.out.println("Fin de la aplicación");
            }

        }while(opcion!=3); 
    }
}

People.java Class

package Ejercicio5;

/**
 *
 * @author nando
 */
public class Personas {

    private String nombre;
    private int añoNac;
    private int añoDef;
    private String areaTrabajo;  

    Personas(String nombre, int añoNac, int añoDef, String areaTrabajo){
        this.nombre = nombre;
        this.añoNac = añoNac;
        this.añoDef = añoDef;
        this.areaTrabajo = areaTrabajo;
    }

    /**
     * @return the nombre
     */
    public String getNombre() {
        return nombre;
    }

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

    /**
     * @return the areaTrabajo
     */
    public String getAreaTrabajo() {
        return areaTrabajo;
    }

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

    /**
     * @return the añoNac
     */
    public int getAñoNac() {
        return añoNac;
    }

    /**
     * @param añoNac the añoNac to set
     */
    public void setAñoNac(int añoNac) {
        this.añoNac = añoNac;
    }

    /**
     * @return the añoDef
     */
    public int getAñoDef() {
        return añoDef;
    }

    /**
     * @param añoDef the añoDef to set
     */
    public void setAñoDef(int añoDef) {
        this.añoDef = añoDef;
    }

}
    
asked by Nando 25.09.2016 в 15:07
source

1 answer

0

When you go to read a number to read a string, before reading it you must release the \n character that remains in the buffer when entering and press enter . So you can understand it better:

  • nextInt() : 1234. Queue in the buffer '\ n
  • nextFloat() : 9845.4. It does not consume \n because it reads floating. It remains in the buffer \n
  • nextLine() : The character \n is consumed
  • Skip the reading of the string because you already read.
  • The solution is to do:

    scanner.nextInt();
    scanner.next(); // se consume el \n
    scanner.nextLine();
    

    Update

    Since you have updated your question to add one more doubt, attach this part.

    Reader

    public class Reader {
    
        private static final Scanner reader = new Scanner(System.in);
    
        public static Scanner get() {
            return reader;
        }
    
        public static void close() {
            reader.close();
        }
    }
    

    Menu

    public class Menu {
    
        public static byte show() {
            byte opcion = 0;
            try  {
                Scanner entrada = Reader.get();
                do {
                    System.out.println("[+] Elegir opción\n");
                    System.out.println("1. Crear ficha de contacto");
                    System.out.println("2. Mostrar contactos");
                    System.out.println("3. Salir\n");
                    opcion = entrada.nextByte();
                    entrada.nextLine(); // consume el \n
                    if(opcion < 1 || opcion > 3) {
                        System.out.println("Opción inválida");
                    }
                } while (opcion < 1 || opcion > 3);
            } catch(NumberFormatException e) {
                System.out.println("Opción inválida");
                Menu.show();
            }
            return opcion;
        }
    }
    

    Person

    public class Persona {
    
        private String nombre;
        private int añoNac;
        private int añoDef;
        private String areaTrabajo;
    
        public Persona() {
    
        }
    
        public Persona(String nombre, int añoNac, int añoDef, String areaTrabajo) {
            this.nombre = nombre;
            this.añoNac = añoNac;
            this.añoDef = añoDef;
            this.areaTrabajo = areaTrabajo;
        }
    
        public String getNombre() {
            return nombre;
        }
    
        public void setNombre(String nombre) {
            this.nombre = nombre;
        }
    
        public String getAreaTrabajo() {
            return areaTrabajo;
        }
    
        public void setAreaTrabajo(String areaTrabajo) {
            this.areaTrabajo = areaTrabajo;
        }
    
        public int getAñoNac() {
            return añoNac;
        }
    
        public void setAñoNac(int añoNac) {
            this.añoNac = añoNac;
        }
    
        public int getAñoDef() {
            return añoDef;
        }
    
        public void setAñoDef(int añoDef) {
            this.añoDef = añoDef;
        }
    
        @Override
        public String toString() {
            return String.format("Nombre:\t%s\nAño de nacimiento:\t%d\n"+
                            "Año de defunción:\t%d\nÁrea de trabajo:\t%s",
                            this.nombre, this.añoNac, this.añoDef, this.areaTrabajo);
        }
    }
    

    Biography

    public class Biografia {
    
        private final List<Persona> contactos = new LinkedList<>();
    
        public void crearContacto() {
    
            try {
                Scanner entrada = Reader.get();
                Persona contacto = new Persona();
    
                System.out.print("\nIntroduzca nombre y apellidos: ");
                contacto.setNombre(entrada.nextLine());
                System.out.print("\nIntroduzca el año de nacimiento: ");
                contacto.setAñoNac(entrada.nextInt());
                System.out.print("\nIntroduzca el año de defunción: ");
                contacto.setAñoDef(entrada.nextInt());
                System.out.print("\nIntroduzca área de trabajo: ");
                entrada.nextLine(); // consume el \n
                contacto.setAreaTrabajo(entrada.nextLine());
    
                contactos.add(contacto);
            } catch(Exception e) {
                e.printStackTrace();
            }
    
        }
    
       public void listarContactos(){
           if(contactos.isEmpty()){
               System.out.println("La lista está vacia");
               return;
           }
           contactos.forEach(System.out::println);
       }
    }
    

    Main

    public class Main {
    
        public static void main(String[] args) {
            Biografia biografia = new Biografia();
            short opcion = Menu.show();
    
            do {
                switch(opcion) {
                    case 1: biografia.crearContacto(); break;
                    case 2: biografia.listarContactos(); break;
                    case 3: Reader.close(); System.exit(0);
                }
                System.out.println();
                opcion = Menu.show();
            } while (opcion != 3);
        }
    
    }
    

    Conclusions

  • The code is the same but object oriented. The reading is encapsulated in class Reader since we will read from 2 classes: Main and Biografia . If we close the Stream of reading, we will not be able to read even if we re-instantiate Scanner (we will obtain a NoSuchElementException ).

  • It is not necessary to return the created contact because it is not used anywhere.

  • The List and LinkedList classes, as well as all family classes, are generic ; that is, they allow you to decide what type of data to store , in this case, objects Persona . What happens if we enter a String? We will get an error when compiling (not even executing).

  • Take advantage of the new Java 8 features (Lambdas, Streams, etc.). Reading a list can now be done in a single line without the need of Iterator .

  • Do not use special / non-English characters in your variables or you will have encoding problems

  • answered by 25.09.2016 / 15:16
    source