Foros del Web » Programación para mayores de 30 ;) » Java »

[SOLUCIONADO] Comparar valores de un ArrayList.

Estas en el tema de Comparar valores de un ArrayList. en el foro de Java en Foros del Web. Estoy creando un código en el que se introducen datos de animales en un ArrayList, y luego, manejar dichos datos. Quiero crear un método que ...
  #1 (permalink)  
Antiguo 26/02/2014, 02:56
 
Fecha de Ingreso: diciembre-2013
Mensajes: 36
Antigüedad: 10 años, 4 meses
Puntos: 1
Pregunta Comparar valores de un ArrayList.

Estoy creando un código en el que se introducen datos de animales en un ArrayList, y luego, manejar dichos datos.
Quiero crear un método que muestre el animal más pesado del registro, pero lo que consigo es que hasta que encuentre el animal más pesado, va mostrando los que son más pesados que el siguiente.

Código del método en cuestión:
Código Java:
Ver original
  1. public static void comparaPeso(ArrayList <Animal> Bestario)
  2.     {
  3.         int i=0,j=1;
  4.  
  5.         Iterator it = Bestario.iterator();
  6.  
  7.         while (it.hasNext())
  8.         {
  9.             it.next();
  10.             if ((Bestario.get(i).peso)>(Bestario.get(j).peso))
  11.             {
  12.                 j++;
  13.                 System.out.println( "Nombre:   " +Bestario.get(i).nombre    +"\n"+
  14.                                     "Pais: " +Bestario.get(i).pais +"\n"+
  15.                                     "Peso: " +Bestario.get(i).peso +"\n"+
  16.                                     "Edad: " +Bestario.get(i).edad  +"\n\n");
  17.             }
  18.             else
  19.             {
  20.                 System.out.println( "Nombre:   " +Bestario.get(j).nombre    +"\n"+
  21.                                     "Pais: " +Bestario.get(j).pais +"\n"+
  22.                                     "Peso: " +Bestario.get(j).peso +"\n"+
  23.                                     "Edad: " +Bestario.get(j).edad  +"\n\n");
  24.             }
  25.             i++;
  26.         }
  27.  
  28.     }

Códigos completos del resto de clases:
Aplicación
Código Java:
Ver original
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package zoo;
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Scanner;
  9.  
  10. /**
  11.  *
  12.  * @author Joan
  13.  */
  14. public class Aplicacion {
  15.  
  16.     /**
  17.      * @param args the command line arguments
  18.      */
  19.     public static void main(String[] args) {
  20.         Scanner teclado=new Scanner(System.in);
  21.        
  22.         Zoologico zoo= new Zoologico();
  23.         ArrayList <Animal> Bestario=new ArrayList<Animal>();
  24.        
  25.         int op=-1, edad;
  26.         String nombre, pais;
  27.         double peso;
  28.        
  29.         /*--------MENU--------*/
  30.         while (op!=0)
  31.         {
  32.            
  33.             do{
  34.  
  35. System.out.println("\n"+"        MENU        ");
  36. verMenu();
  37. op=teclado.nextInt();
  38.  
  39.  
  40. switch(op){
  41.  
  42.                 case 1: zoo.anyadeAnimal(Bestario);
  43.                         break;
  44.  
  45.                 case 2: zoo.mostrarAnimales(Bestario);
  46.                         break;
  47.  
  48.                 case 3: zoo.comparaPeso(Bestario);
  49.                         break;
  50.  
  51.                 case 4: ;
  52.                         break;
  53.  
  54.                 case 0: System.out.println("Se ha cerrado el programa.");
  55.                         break;
  56.    
  57. default: System.out.println("Error" ); break;
  58.  
  59. }
  60. }while(op!=0);
  61.            
  62.     }
  63.        
  64.     }
  65.     public static void verMenu(){
  66.          System.out.println("1.Añadir  Animal.");
  67.          System.out.println("2.Mostrar Animales.");
  68.          System.out.println("3.Mostrar Animal más pesado.");
  69.          System.out.println("4.");
  70.          System.out.println("0.Salir");
  71.          
  72.    }
  73. }

Animal
Código Java:
Ver original
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package zoo;
  6.  
  7. /**
  8.  *
  9.  * @author User
  10.  */
  11. public class Animal {
  12.    
  13.     String nombre, pais;
  14.     double peso;
  15.     int edad;
  16.    
  17.     public Animal(){
  18.         this.nombre="";
  19.         this.pais="";
  20.         this.peso=0.00;
  21.         this.edad=0;
  22.     }
  23.    
  24.     public Animal(String nom, String pais, double peso, int edad){
  25.         this.nombre=nom;
  26.         this.pais=pais;
  27.         this.peso=peso;
  28.         this.edad=edad;
  29.     }
  30.    
  31.     /*----------GETS-SETS----------*/
  32.  
  33.     public String getNombre() {
  34.         return nombre;
  35.     }
  36.  
  37.     public void setNombre(String nombre) {
  38.         this.nombre = nombre;
  39.     }
  40.  
  41.     public String getPais() {
  42.         return pais;
  43.     }
  44.  
  45.     public void setPais(String pais) {
  46.         this.pais = pais;
  47.     }
  48.  
  49.     public double getPeso() {
  50.         return peso;
  51.     }
  52.  
  53.     public void setPeso(double peso) {
  54.         this.peso = peso;
  55.     }
  56.  
  57.     public int getEdad() {
  58.         return edad;
  59.     }
  60.  
  61.     public void setEdad(int edad) {
  62.         this.edad = edad;
  63.     }
  64.     /*------------------------------------------------------------------------*/
  65.    
  66. }

Zoológico
Código Java:
Ver original
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package zoo;
  6. import java.util.*;
  7.  
  8. /**
  9.  *
  10.  * @author Joan
  11.  */
  12. public class Zoologico {
  13.     //Vector v = new Vector (3/1);
  14.     ArrayList <Animal> Bestario;
  15.    
  16.     /*public Zoologico(){
  17.     }*/
  18.    
  19.     public Zoologico() {
  20.     Bestario = new ArrayList<>();
  21.     }
  22.    
  23.     public void anyadeAnimal(ArrayList <Animal> Bestario){
  24.         Animal ficha;
  25.         ficha=new Animal();
  26.         //v.addElement(a);
  27.        
  28.         Scanner leer = new Scanner(System.in);
  29.  
  30.         System.out.println("Introduce su nombre: ");
  31.         ficha.nombre=leer.nextLine();
  32.        
  33.         System.out.println("Introduce su país de procedencia: ");
  34.         ficha.pais=leer.nextLine();
  35.        
  36.         System.out.println("Introduce su peso: ");
  37.         ficha.peso=leer.nextDouble();
  38.        
  39.         System.out.println("Introduce su edad:");
  40.         ficha.edad=leer.nextInt();
  41.  
  42.        
  43.         Bestario.add(ficha);
  44.     }
  45.    
  46.     public static void mostrarAnimales(ArrayList <Animal> Bestario){
  47.         int i=0;
  48.  
  49.         Iterator it = Bestario.iterator(); //Porque utilizar esto --> http://goo.gl/EfvDx0
  50.         if (!it.hasNext())
  51.             System.out.println("No Hay Animales en el registro."+"\n");
  52.         else
  53.          while (it.hasNext())
  54.          {
  55.             it.next();
  56.             System.out.println("Animal nº: " +(i+1)                      +"\n"+
  57.                                "Nombre:   " +Bestario.get(i).nombre    +"\n"+
  58.                                "Pais: " +Bestario.get(i).pais +"\n"+
  59.                                "Peso: " +Bestario.get(i).peso +"\n"+
  60.                                "Edad: " +Bestario.get(i).edad  +"\n\n");
  61.             i++;
  62.          }
  63.     }
  64.    
  65.     public static void comparaPeso(ArrayList <Animal> Bestario)
  66.     {
  67.         int i=0,j=1;
  68.  
  69.         Iterator it = Bestario.iterator();
  70.  
  71.         while (it.hasNext())
  72.         {
  73.             it.next();
  74.             if ((Bestario.get(i).peso)>(Bestario.get(j).peso))
  75.             {
  76.                 j++;
  77.                 System.out.println( "Nombre:   " +Bestario.get(i).nombre    +"\n"+
  78.                                     "Pais: " +Bestario.get(i).pais +"\n"+
  79.                                     "Peso: " +Bestario.get(i).peso +"\n"+
  80.                                     "Edad: " +Bestario.get(i).edad  +"\n\n");
  81.             }
  82.             else
  83.             {
  84.                 System.out.println( "Nombre:   " +Bestario.get(j).nombre    +"\n"+
  85.                                     "Pais: " +Bestario.get(j).pais +"\n"+
  86.                                     "Peso: " +Bestario.get(j).peso +"\n"+
  87.                                     "Edad: " +Bestario.get(j).edad  +"\n\n");
  88.             }
  89.             i++;
  90.         }
  91.  
  92.     }
  #2 (permalink)  
Antiguo 26/02/2014, 14:26
Avatar de Xerelo  
Fecha de Ingreso: mayo-2009
Mensajes: 2.175
Antigüedad: 15 años
Puntos: 306
Respuesta: Comparar valores de un ArrayList.

Tienes muchas opciones

Recorrer todos los elementos y almacenar el de mayor peso según vas comparando cada elemento, y pintarlo al salir del bucle.

También puedes ordenar la lista en función del peso

Así

http://docs.oracle.com/javase/7/docs...omparable.html

o así

http://docs.oracle.com/javase/7/docs...omparator.html
__________________
Cada vez que solucionas los problemas de alguien que no se esfuerza, piensa en que el día de mañana puede llegar a ser tu compañero de trabajo, o peor, tu jefe.
  #3 (permalink)  
Antiguo 06/03/2014, 01:19
 
Fecha de Ingreso: diciembre-2013
Mensajes: 36
Antigüedad: 10 años, 4 meses
Puntos: 1
Respuesta: Comparar valores de un ArrayList.

Gracias por la ayuda.

Etiquetas: arraylist, clases
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:13.