Simple circular lists, count and show

1

is my first question within this community and in advance I appreciate all the help you can give me.

At this moment I have the need in Java to count the elements of a simple circular list that match a parameter and show that amount on the screen, so I also need to show the games based on another parameter, in this case the price. In this way I must develop the following methods in Java

    Public int contar (String plataforma){
    }
    Public void mostrar (int precio){
    }

As a reference, my list is composed of the following elements.

    Lista_circular lista = new Lista_circular();
    lista.inserta(new Juego ("Deportes", "PES 2015", "PS3", 30, 7.8f));
    lista.inserta(new Juego ("Aventura", "God of War SAGA", "PS3", 40, 8.7f));
    lista.inserta(new Juego ("Supervivencia", "The Last of US", "PS3", 60, 9.2f));
    lista.inserta(new Juego ("Aventura", "GTA V", "PS3", 60, 8.3f));
    lista.inserta(new Juego ("Indie", "Inside + Limbo", "PS4", 70, 8.3f));
    lista.inserta(new Juego ("Aventura", "Bioshock - The Collection", "PS4", 55, 9.0f));

Inside the Circular_list class I have the following.

public class Lista_circular {
private Nodo cabeza, ultimo;


//Método encargado de insertar juegos en la lista circular
public void inserta(Juego j){
    //si el valor de cabeza es nulo, es decir, la lista está vacía el juego
    //toma el valor de j
    if (cabeza == null){
        cabeza = new Nodo (j); 
        //a la vez el último es el primero dentro de la lista
        ultimo = cabeza;
        //se establece que el ultimo tiene como siguiente a cabeza
        ultimo.setNext(cabeza);
    //si ya hay un valor en cabeza al momento de agregar un juego
    }else{
        //el juego a ingresar se acomoda de tal manera que el precio menor 
        //vaya a la izquierda del ya ingresado         
        if(j.getPrecio() < cabeza.getDato().getPrecio()){
            //se crea un aux para unir los juegos
            Nodo aux = new Nodo (j); 
            aux.setNext(cabeza);
            cabeza = aux;
            //con esto hacemos la lista circular   
            ultimo.setNext(cabeza); 
            //para insertar todos los datos mayor
        }else{ 
            //valida si el precio del nuevo juego a insertar tiene un precio
            //mayor al último ingresado
            if (j.getPrecio() >= ultimo.getDato().getPrecio()){ 
                //No se pueden unir nodos y juegos, por ello crearemos el nodo auxiliar
                Nodo aux = new Nodo (j);
                ultimo.setNext(aux);
                ultimo = aux; 
                ultimo.setNext(cabeza); //circular de nuevo 
                //para insertar en el medio de la estructura
            }else{ 
                Nodo aux = cabeza;
                while(j.getPrecio() > aux.getNext().getDato().getPrecio() ){ //el precio del juego es mayor al siguiente del auxiliar
                    aux = aux.getNext(); 
                }
                Nodo temp = new Nodo (j); //creamos el dato temporal para guardar el juego entre dos precios, una vez cerrado el ciclo
                //se une primero el juego menor con el mayor para no perder la listya
                temp.setNext(aux.getNext());
                aux.setNext(temp); //se une el menor con el mayor en dicha comparacion
            }  
        }
    }        

}

//Método encargado de validar si un juego existe dentro de la lista
public boolean existe (String nombre){
    String mensaje;
    boolean existe = false;
    Nodo aux = cabeza;
    if (cabeza == null) {
        mensaje = "La lista no contiene datos";
    } else {
        if (nombre.equals(aux.getDato().getNombre())) {
            existe = true;
        }
        aux = aux.getNext();
        while (aux != cabeza) {
            if (nombre.equals(aux.getDato().getNombre())) {
                existe = true;
            }
            aux = aux.getNext();
        }
    }
    return existe;
}

//Método encargado de moficiar en base a nombre y plataforma
public void modifica (String nombre, String plataforma){
    String mensaje = "";
    boolean existe = false;
    Nodo aux = cabeza;
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    }
    else {
        if (nombre.equals(aux.getDato().getNombre()) && plataforma.equals(aux.getDato().getPlataforma()) ){
            aux.getDato().setPuntaje(10);
            existe = true;
        }
        aux = aux.getNext();
        while (aux != cabeza) {
            if (nombre.equals(aux.getDato().getNombre()) && plataforma.equals(aux.getDato().getPlataforma()) ) {
                aux.getDato().setPuntaje(10);
                existe = true;
            }
            aux = aux.getNext();
        }
    }
    if (existe == false) {
        System.out.println("No existe un juego con las caracteristicas indicadas");
    }
}

//Método encargado de eliminar en base a categoria y nombre
public void elimina (String categoria, String nombre){
    String mensaje = "";
    boolean existe = false;
    Nodo aux = cabeza;
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    } else {
        if (categoria.equals(aux.getDato().getCategoria()) && nombre.equals(aux.getDato().getNombre())) {
            cabeza = aux.getNext();
            ultimo.setNext(cabeza);
            existe = true;
        } else if (categoria.equals(aux.getDato().getCategoria()) && nombre.equals(aux.getDato().getNombre())) {
            aux.setNext(aux.getNext().getNext());
            existe = true;
        }
        aux = aux.getNext();
        while (aux != cabeza) {
            if (categoria.equals(aux.getDato().getCategoria()) && nombre.equals(aux.getDato().getNombre())) {
                aux.setNext(aux.getNext().getNext());
                existe = true;
            }
            aux = aux.getNext();
        }
    }
    if (existe == false) {
        System.out.println("No existe un juego que coincida con la categoria y nombre indicados");
    }
}

//Método encargado de contar los elementos que coincidan con plataforma
public int contar (String plataforma){
    String mensaje = "";
    boolean existe = false;
    Nodo aux = cabeza;
    int cont = 0;
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    }else{                        
        if (plataforma.equals(aux.getDato().getPlataforma())){
            cont++;
            existe = true;
        } else {
            aux = aux.getNext();
            while (aux != cabeza) {
                if (plataforma.equals(aux.getDato().getPlataforma())) {                        
                    existe = true;  
                }
                cont++;
                aux = aux.getNext();
            }
                }
        if (existe == false) {
            System.out.println("No existen juegos de dicha plataforma");
            return 0;
            }                        
        }
    return cont;

}

//Método encargado de mostrar en base al precio
public void mostrar (int precio){
    String mensaje = "";
    boolean existe = false;
    Nodo aux = cabeza;
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    }else{
        if (precio == aux.getDato().getPrecio()){
            System.out.println(aux.getDato().getPrecio());
        }
    }
}



//Imprime en consola
 @Override
public String toString() {
    Nodo aux = cabeza;
    String s = "Lista: \n ";
    if (aux != null) {
        s += aux + ", \n ";
        aux = aux.getNext();
        while (aux != cabeza) {
            s += aux + ", \n ";
            aux = aux.getNext();
        }
    } else {
        s+= "Vacia";
    }
    return s;
}    

}

This way I have inside the main the following that allows me to print in console the different methods created.

    public static void main(String[] args) {

    Lista_circular lista = new Lista_circular();
    lista.inserta(new Juego ("Deportes", "PES 2015", "PS3", 30, 7.8f));
    lista.inserta(new Juego ("Aventura", "God of War SAGA", "PS3", 40, 8.7f));
    lista.inserta(new Juego ("Supervivencia", "The Last of US", "PS3", 60, 9.2f));
    lista.inserta(new Juego ("Aventura", "GTA V", "PS3", 60, 8.3f));
    lista.inserta(new Juego ("Indie", "Inside + Limbo", "PS4", 70, 8.3f));
    lista.inserta(new Juego ("Aventura", "Bioshock - The Collection", "PS4", 55, 9.0f));
    //Lista circular original
    System.out.println("---LISTA ORIGINAL---");
    System.out.println(lista.toString());
    //Buscar un juego con el nombre
    System.out.println("---BUSQUEDA DE JUEGO BASADO EN EL NOMBRE---");
    System.out.println("¿El juego ingresado existe? \n"+lista.existe("PES 2018"));
    System.out.println("\n");
    //Modifica el puntaje de un juego dado un nombre y plataforma
    System.out.println("---MODIFICACIÓN DEL PUNTAJE BASADO EN 2 CAMPOS---");
    System.out.println("Modificación del puntaje dado un juego y plataforma dado");
    lista.modifica("Inside + Limbo", "PS4");
    System.out.println("Lista después de modificación:\n" + lista);        
   //Elimina un juego dada una categoría y un nombre
    System.out.println("---ELIMINACIÓN DE JUEGO BASADO EN EL NOMBRE---");
    System.out.println("Elimina por ID");
    lista.elimina("Deportes", "PES 2015");
    System.out.println("Lista después de eliminación:\n"+lista);
    //Indica cuantos juegos existen de una plataforma
    System.out.println("---CONTEO DE JUEGOS SEGÚN PLATAFORMA---");
    System.out.println("Para la plataforma indicada se encontraron: "  +lista.contar("PS3"));
    //
    System.out.println("", +lista.mostrar(7));

}

However, when I print the counting method, I get a different number than expected, within normal it would be that if I put "PS3" as a parameter I should return to me that there are 4 games in the list that match the indicated , however, the result returns one, and if I put "PS4" inside the parameter it returns as result 4

--- COUNTING OF GAMES ACCORDING TO PLATFORM --- For the indicated platform they found: 4

With regard to the method show should show me each of the games that match a price less than or equal to the indicated and print those games on the screen, but likewise here the method does not let me enter the price I want and get as an error in the main

"void type not allowed here"

    
asked by Fabian Montero Perez 01.03.2018 в 15:49
source

1 answer

1

Let's see ...

The count method has a serious logic defect.

If your first item is the one you are looking for, do not count anymore and stop searching.

public int contar (String plataforma){
...
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    }else{    
    //Aca esta el problema.. si el primero es lo que buscas, ya te fuiste.                    
    if (plataforma.equals(aux.getDato().getPlataforma())){
        cont++;
        existe = true;
    } else {
        aux = aux.getNext();
        while (aux != cabeza) {
            if (plataforma.equals(aux.getDato().getPlataforma())) {                        
                existe = true;  
            }
            cont++;
            aux = aux.getNext();
        }

Very quick solution to this .. Take the else (and the else's code goes outside the if), and it will walk perfectly without you noticing why (and as a task, try to understand why) .

Your code should look like this:

public int contar (String plataforma){
...
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    }else{    
    //Aca esta el problema.. si el primero es lo que buscas, ya te fuiste.                    
    if (plataforma.equals(aux.getDato().getPlataforma())){
        cont++;
        existe = true;
    } 
    aux = aux.getNext();
    while (aux != cabeza) {
        if (plataforma.equals(aux.getDato().getPlataforma())) {                        
            existe = true;  
        }
        cont++;
        aux = aux.getNext();
    }

The show function does not do anything at all .. but what a coincidence, the count function has the same logic, only that instead of showing, it counts ..

And if, say, you use the count function code .. but instead of counting (or adding to the cont ++), you show ????

After a couple of revisions, finally the code of the counting method was as follows.

    public int contar(String plataforma) {
    String mensaje = "";
    boolean existe = false;
    Nodo aux = cabeza;
    int cont = 0;
    if (cabeza == null) {
        mensaje = "La lista está vacía";
    } else {

        if (plataforma.equals(aux.getDato().getPlataforma())) {
            cont++;
            existe = true;
        }
        aux = aux.getNext();
        while (aux != cabeza) {
            if (plataforma.equals(aux.getDato().getPlataforma())) {
                existe = true;
                cont++;
            }
            aux = aux.getNext();
        }
        if (existe == false) {
            System.out.println("No existen juegos de dicha plataforma");
            return 0;
        }
    }
    return cont;
}

Now I just have to finish the show and it would be ready

    
answered by 01.03.2018 / 17:33
source