How to browse a java chained list

Asked

Viewed 643 times

-2

I need to go through a chained list to compare whether the number the user will enter is equal to an attribute of a class (doctors) that has a chained list.

I have the following Classes: Node, Simple List, Doctors and System.

The error is in case 2 of the System, I’m trying to use an attribute like Node that is in List_simple to go through (aux is taking the value of first that I called Prim), but I believe that maybe this shouldn’t be the right way to go through.

Knot class:

public class No {
    private Medicos m;
    private No prox; 

public No(Medicos me) {
    this.setM(me);
    this.setProx(null);
}
}

Simple List Class:

public class Lista_Simples {
private No prim;        //Primeiro nó
private No ult;         //Último nó
private int qntdno;     //Quantidade de nós
private No aux;

 Medicos M = new Medicos();

//Construtor
public Lista_Simples(){
    this.prim = null;    //Iniciando com null
    this.ult = null;     //Iniciando com null
    this.qntdno = 0;     //Iniciando com 0
    this.aux = this.prim;
}

//Saber se a lista é vazia, se estiver nulo então é criado o primeiro nó
public boolean listavazia () {
    return (this.prim == null);
}


public void inserirPrimeiro(Medicos p) {
    No novoNo = new No(p);
    //Se a lista não for vazia o primeiro nó também é o último
    if(this.listavazia()){
        this.ult = novoNo;
    }
    novoNo.setProx(this.prim);      //O próximo nó se tornará o primeiro nó
    this.prim = novoNo;             //O novo primeiro será novoNo
    this.qntdno++;                  //Incrementando a contagem de quantidade de nós
}
public No getAux() {
    return aux;
}

public void setAux(No aux) {
    this.aux = prim;
}

}

Medical Class:

public class Medicos {

private String nome;
private int crm;

public int getCrm() {
    return crm;
}

public void setCrm(int crm) {
    this.crm = crm;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}
}

System Class:

  public class Sistema {
//static Pacientes P;
//Medicos m;
//m = new Medicos();
//private int crmnovo = 0;


public static void main(String[] args) {

    //Pacientes P = new Pacientes();
    Lista_Simples ListaPacientes = new Lista_Simples();
    Lista_Simples ListaMedicos = new Lista_Simples();


    while(true) {
        System.out.println("Escolha a ação que deseja executar:"
                + "\n1-Cadastrar Paciente"
                + "\n2-Cadastrar Médico"
                + "\n3-Editar dados do Médico");
        System.out.println("Digite o número da ação que deseja executar: ");
        Scanner menu = new Scanner(System.in);
        int acao = menu.nextInt();

        Medicos M = new Medicos();

        switch(acao) {
            case 1:
                int fim2 = 0;

                Scanner nomeM = new Scanner(System.in);
                System.out.println("\nDigite o nome do médico:");
                String nomemedico = nomeM.nextLine();
                M.setNome(nomemedico);
                System.out.println("\nO nome é "+M.getNome());

                Scanner crmM = new Scanner(System.in);
                System.out.println("\nDigite o CRM do médico:");
                String crm = crmM.nextLine();
                M.setNome(crm);
                System.out.println("\nO CRM é "+M.getCrm());

                do {
                    ListaMedicos.inserirPrimeiro(M);
                    fim2++;
                    break;
                }while(fim != 0);

                System.out.println(ListaMedicos.imprimirLista(M));

                break;

            case 2: 
                //Medicos M = new Medicos();
                System.out.println("\nDigite o seu CRM: ");
                Scanner editar = new Scanner(System.in);
                int crmexiste = editar.nextInt();
                //System.out.println("\n"+crmexiste);
                while (ListaMedicos.M.getCrm() != crmexiste) {
                    if (crmexiste != ListaMedicos.M.getCrm()){
                        //O ERRO ESTÁ AQUI, BASICAMENTE EU NÃO CONSIGO PERCORRER A LISTA DE MÉDICOS, TEM ALGUNS CÓDIGOS QUE COMENTEI AQUI QUE DERAM ERRADO
                        System.out.println("Erro aqui!");
                        //ListaMedicos.getAux().setProx(ListaMedicos.getAux());
                        ListaMedicos.getAux().getProx();
                        System.out.println(ListaMedicos.getAux());

                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                    }
                    else {
                        //M2.getListademdc().pesquisarNo(crmexiste);
                        System.out.println("\nDigite o seu CRM: ");
                        Scanner novo = new Scanner(System.in);
                        int novocrm = novo.nextInt();
                        ListaMedicos.M.setCrm(novocrm);
                    }
                }
                break;

        }
    }
}
}

Thanks in advance for your help!

  • Does your action "register patient", creates a new doctor? And you need to use chained list or can solve with another structure?

1 answer

2


You can’t go through the list of doctors because you’re accessing the object Medicos who is in your ListaSimples and not the doctors of each node. No need to create a doctor in your class ListaSimples, so remove this line from this class: Medicos M = new Medicos();

1) Before going through the list of doctors, we will fill it out correctly.

Build an object Medicos new every time you register a new doctor. As it is there, you have created an object and are modifying it every time you call case 1. So, move your line Medicos M = new Medicos(); for the beginning of your case 1, being like this Let yours case 1 thus:

2) Go through the list

To scroll through the list, you must go node by node, so your case 2 while won’t work. Your System class with the changes would basically look like this:

public class Sistema {
//static Pacientes P;
//Medicos m;
//m = new Medicos();
//private int crmnovo = 0;


public static void main(String[] args) {

    //Pacientes P = new Pacientes();
    Lista_Simples ListaPacientes = new Lista_Simples();
    Lista_Simples ListaMedicos = new Lista_Simples();


    while(true) {
        System.out.println("Escolha a ação que deseja executar:"
                + "\n1-Cadastrar Paciente"
                + "\n2-Cadastrar Médico"
                + "\n3-Editar dados do Médico");
        System.out.println("Digite o número da ação que deseja executar: ");
        Scanner menu = new Scanner(System.in);
        int acao = menu.nextInt();

        switch(acao) {
            case 1:
                int fim2 = 0;
                // LINHA MOVIDA
                Medicos M = new Medicos();

                Scanner nomeM = new Scanner(System.in);
                System.out.println("\nDigite o nome do médico:");
                String nomemedico = nomeM.nextLine();
                M.setNome(nomemedico);
                System.out.println("\nO nome é "+M.getNome());

                Scanner crmM = new Scanner(System.in);
                System.out.println("\nDigite o CRM do médico:");
                String crm = crmM.nextLine();
                M.setNome(crm);
                System.out.println("\nO CRM é "+M.getCrm());

                do {
                    ListaMedicos.inserirPrimeiro(M);
                    fim2++;
                    break;
                }while(fim != 0);

                System.out.println(ListaMedicos.imprimirLista(M));

                break;

            case 2: 
                //Medicos M = new Medicos();
                System.out.println("\nDigite o seu CRM: ");
                Scanner editar = new Scanner(System.in);
                int crmexiste = editar.nextInt();
                //System.out.println("\n"+crmexiste);

                No no = ListaMedicos.getPrim();

                // NOVO WHILE
                while (no != null && no.getMedicos().getCrm() != crmexiste) {
                    if (crmexiste != ListaMedicos.M.getCrm()){
                        //O ERRO ESTÁ AQUI, BASICAMENTE EU NÃO CONSIGO PERCORRER A LISTA DE MÉDICOS, TEM ALGUNS CÓDIGOS QUE COMENTEI AQUI QUE DERAM ERRADO
                        System.out.println("Erro aqui!");
                        //ListaMedicos.getAux().setProx(ListaMedicos.getAux());
                        ListaMedicos.getAux().getProx();
                        System.out.println(ListaMedicos.getAux());

                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                        //ListaMedicos.setAux(ListaMedicos.getAux().getProx());
                    }
                    else {
                        //M2.getListademdc().pesquisarNo(crmexiste);
                        System.out.println("\nDigite o seu CRM: ");
                        Scanner novo = new Scanner(System.in);
                        int novocrm = novo.nextInt();
                        ListaMedicos.M.setCrm(novocrm);
                    }
                }
                // PASSA PARA O PRÓXIMO NÓ
                no = no.getProx();
                break;

        }
    }
}
}

Looking at your classes, you will need to create the getters used in each one (getProx(), getMedicos() and getPrim())

Tip: There are a lot of things there that could be improved and some good practices could be applied, so a researched on when you can. Follow a link about chained lists tbm that will help.

https://www.caelum.com.br/apostila-java-estrutura-dados/listas-ligadas/

  • About the getters I already have them, only I did not put here not to get something tiring after all can be generated by the IDE itself. How can I use Medicos M = new Medicos(); in the second case? Here it appears as if it were a "local variable" (I don’t know very well about java, I know it is not a variable but an object) of case 1

  • Oh yes, I got it. You can leave the M statement in your class and the initialization of the object at the necessary time. The important thing is that it be a new object, a new reference. But what would be the need to have a new Doctor in case 2?

  • Your business logic remained the same, but it explains what you want to do when case 2.

  • Basically I was testing how it worked, so I left as a comment there in 2, besides I left the New Medicos in general there (a kind of global) so that I could use both in the registration case and in the edition. I want to thank you, you were patient (since many users often complain of poorly elaborated description, I tried to make mine simpler and even then I was negatived, I think I can improve even more) and strove for a problem of another person. Thank you very much for your help!

  • 1

    Got it. The problem of leaving in general is that you will work on the same object always. If you do not create a new object (new Medicos()) every time you register a new one, it will change that existing object, understand? Already in the editing part you will need to fetch the object and not create a new one. If you’re still a little confused, let me know and I’ll explain it to you. Dispose, the purpose here is to really help. Hugs]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.