java - 在 java LinkedList 节点中存储超过 1 个数据项,并使用 .toString() 将它们显示为字符串

标签 java linked-list

我正在做一个如下的编程项目:

处理学生注册的系统。注册时,您必须提供名字和姓氏、身份证号码、地址、电话、电子邮件和 2 节类(class)的代码才能注册。这应该存储在 LinkedList 中。

因为 LinkedList 中的每个节点只能存储一个数据,所以我决定更进一步。使用this答案作为基础我做了改变,我没有将每个学生8的8个学生数据存储在每个注册学生的8个连续节点中,而是创建了一个具有8个属性的对象,它存储每个学生注册的8个数据,所以当您想要删除学生时,只需删除包含该对象的节点即可,而不是为每个要删除的学生删除 8 个连续节点。

当我将学生数据添加到对象上,然后添加到 LinkedList 节点上时,这个想法非常有效,但是,当我需要在屏幕上显示所有学生时,该技术就会失败。

理论上,通过使用迭代器方法 .hasNext() 和 .Next(),列表将迭代并在屏幕上显示存储在节点中的对象的内容,而且确实如此......但以散列而不是字符串的形式(我需要的)。因此,在屏幕上,而不是显示类似

Angel Pérez 15956228 7274205 skyx26@yahoo.com Caracas
Carolina Rojas 13508200 6253241 caro_caro27@hotmail.com Maracaibo

I get

PaqueteDeDatos@158b649
PaqueteDeDatos@127734f

After much searching I was told (here) that happens because

And the "...@..." stuff is printed because that is what the default version of toString gives you. If you want something pretty, you'll have to override the toString() method in your PaqueteDeDatos class

Problem is that I can not use an iterator to display the contents of all nodes at the same time to make the override .toString ().

Help me with this please, I need to display the contents of the nodes of the linkedList as string and not as hash.

Please please please explain me as easy as you can what I need to do to solve this, I don't really understand Java, I can't buy a book to understand it nor go to a public library to get one. I don't have friends who code in java so I can't ask for help to anyone and I need to get this done in the next 24 hours.

And please be constructive and kind. I don't really need to be spanked because I don't follow conventions or go to java site and follow tutorials before start coding in java. In fact I know all that but this is a rush situation and I running blind trying to pass this class because my programming teacher haven't teach me ANYTHING at all.

I'm using the code below (ONLY OPTIONS 1, 4 and 5 WORKS):

import java.util.*;

class PaqueteDeDatos {
    String Nombre;
    String Apellido;
    String Cedula;
    String Direccion;
    String Telefono;
    String CorreoElectronico;
    String Intensivo1;
    String Intensivo2;

   public PaqueteDeDatos(String a, String b, String c, String d, String e, String f, String g, String h) {
       Nombre = a;
       Apellido = b;
       Cedula = c;
       Direccion = d;
       Telefono = e;
       CorreoElectronico = f;
       Intensivo1 = g;
       Intensivo2 = h;
   }
}


public class Proyecto{

    public static void main(String[] args) {
        System.out.println ("┌──────────────────────────────────────────────────────────────────┐");
        System.out.println ("│                               Manejo de listas dinamicas en Java                                       │");
        System.out.println ("├──────────────────────────────────────────────────────────────────┤");
        System.out.println ("│Aplicacion que controla la informacion asociada a estudiante a inscribirse en un posible curso intensivo│");
        System.out.println ("└──────────────────────────────────────────────────────────────────┘");
        //Pausa();
        LinkedList<PaqueteDeDatos> ListaDeAlumnos = new LinkedList<PaqueteDeDatos>();
        while (true) {
        for (int i=0; i<25; ++i) System.out.println();


        MenuPrincipal();
        Scanner CapturaDeDatos = new Scanner(System.in);
        System.out.print ("Introduzca su opcion: ");
        char Opcion = CapturaDeDatos.next().charAt(0);
        if (Opcion !='1' && Opcion !='2' && Opcion !='3' && Opcion !='4' && Opcion !='5') {
            System.out.println("Opcion invalida. Por favor introduzca nuevamente su eleccion...");
            Pausa();
        }
        if (Opcion =='1') {
            for (int i=0; i<25; ++i) System.out.println();
            System.out.print ("Introduzca el nombre del alumno: ");
            String Nombre = CapturaDeDatos.next();
            System.out.println ();
            System.out.print ("Introduzca el apellido del alumno: ");
            String Apellido = CapturaDeDatos.next();
            System.out.println ();
            System.out.print ("Introduzca el numero de cedula del alumno: ");
            String Cedula = CapturaDeDatos.next();
                System.out.println ();
            System.out.print ("Introduzca la direccion de habitacion del alumno: ");
            String Direccion = CapturaDeDatos.next();
            System.out.println ();
            System.out.print ("Introduzca el telefono de contacto del alumno: ");
            String Telefono = CapturaDeDatos.next();
            System.out.println ();
            System.out.print ("Introduzca el correo electronico del alumno: ");
            String CorreoElectronico = CapturaDeDatos.next();
            System.out.println ();
            System.out.println ("A continuacion introduzca los intensivos a cursar por el alumno, basandose en la tabla superior.");
            System.out.println ("Tenga en cuenta que solo se pueden inscribir MAXIMO 2 intensivos. Para evitar retrazos en el inicio");
            System.out.println ("de los intensivos, procure que los intensivos escogidos por el alumno no choquen entre si");
            System.out.println ("por tener los mismos horarios. Introduzca 00 (2 ceros) luego del primer intensivo, si el alumno solo");
            System.out.println ("va a cursar un intensivo...");
            System.out.println ();
            System.out.print ("Introduzca el codigo del intensivo seleccionado por el alumno: ");
            String Intensivo1 = CapturaDeDatos.next();
            System.out.println ();
            System.out.print ("Introduzca el codigo del intensivo seleccionado por el alumno: ");
            String Intensivo2 = CapturaDeDatos.next();
            System.out.println ();
            PaqueteDeDatos Alumno = new PaqueteDeDatos (Nombre,Apellido,Cedula,Direccion,Telefono,CorreoElectronico,Intensivo1,Intensivo2);
            ListaDeAlumnos.add(Alumno);
            System.out.println ("Alumno inscrito exitosamente.");
            System.out.println ("El sistema regresara al menu principal en 5 segundos...");
            Pausa();
        }
//        if (Opcion =='2') {
//
//        }
  //      if (Opcion =='3') EliminarAlumno();
        if ((int) Opcion =='4') {
            Iterator Iterador = ListaDeAlumnos.iterator();
            while (Iterador.hasNext())
                System.out.println (Iterador.next());
            System.out.println ("Listado de alumnos mostrado exitosamente.");
            System.out.println ("El sistema regresara al menu principal en 5 segundos...");
            Pausa();
            for (int i=0; i<25; ++i) System.out.println();
            MenuPrincipal();
            System.out.print ("Introduzca su opcion: ");
            Opcion = CapturaDeDatos.next().charAt(0);

        }
        if (Opcion =='5') System.exit(0);
        }
    }

    // Metodo para la pausa en pantalla
    public static void Pausa() {
        try {
            Thread.sleep(5000);
        }
        catch (InterruptedException ex) {
        }
    }

       // Metodo para el menu principal
    public static void MenuPrincipal() {
        System.out.println ("╔════════════════════╗");
        System.out.println ("║         Menu Principal        ║");
        System.out.println ("╠════════════════════╣");
        System.out.println ("║                               ║");
        System.out.println ("╠════════════════════╣");
        System.out.println ("║       Inscribir Alumno    (1) ║");
        System.out.println ("╠════════════════════╣");
        System.out.println ("║       Modificar Alumno    (2) ║");
        System.out.println ("╠════════════════════╣");
        System.out.println ("║       Eliminar Alumno     (3) ║");
        System.out.println ("╠════════════════════╣");
        System.out.println ("║ Mostrar Alumnos Inscritos (4) ║");
        System.out.println ("╠════════════════════╣");
        System.out.println ("║      Salir del sistema    (5) ║");
        System.out.println ("╚════════════════════╝");
            System.out.println ();
    }

}

最佳答案

使类可打印或能够使用 toString() 的正常方法是重写该类的 toString() 方法。最简单的方法是让 IDE 生成 toString() 方法。其他事情可能会更困难。

如果您无法更改代码以添加 toString(),您可以编写自己的方法来将对象列表转换为字符串,该字符串检查列表中的每个元素并按照您想要的方式进行转换。

关于java - 在 java LinkedList 节点中存储超过 1 个数据项,并使用 .toString() 将它们显示为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4930933/

相关文章:

java - HTTP ERROR 503 服务在 Jetty 服务器中不可用

java - 添加keylistener返回空指针异常

java - "Recursive"listToString()-链表中的方法

java - 在 Hibernate 中使用复合主键映射集合

java - 是否有在 IntelliJ 中使用 system.out.println 包装语句的快捷方式

java - ArrayList克隆仍然被引用?

c - 理解c中的链表结构

创建一个链表来注册 C 学生

java - int/String 链表和变量的问题

c - 链表还是顺序内存?