Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2017
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.33 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. import javax.jws.Oneway;
  4.  
  5.  
  6. public class Aplicacion {
  7.  
  8.    
  9.     public static void main(String[] args) {
  10.    
  11.        
  12.         System.out.println("Bienvenido al programa!");
  13.        
  14.         /** Aquí tenemos el Arraylist */
  15.         ArrayList<Objeto> miArrayList = new ArrayList<Objeto>();  
  16.        
  17.         boolean salir = false;
  18.        
  19.         while(!salir){
  20.            
  21.             System.out.println("========== MENÚ ==========");
  22.             System.out.println("1) Ingresar ##OBJETO## ");
  23.             System.out.println("2) Buscar y mostrar datos de un ##OBJETO## por su ##IDENTIFICADOR## ");
  24.             System.out.println("3) Encontrar el objeto que cumpla ##CARACTERÍSTICA (MÁS GRANDE, MÁS CHICO, ETC.## ");
  25.             System.out.println("4) Encontrar el ##TOTAL DE ALGO## ");
  26.            
  27.            
  28.            
  29.             int op1 = Leer.datoInt();
  30.            
  31.             switch(op1){
  32.            
  33.             /****************************************/
  34.             /** INICIO DEL CASO 1: INGRESAR OBJETO **/
  35.             /****************************************/
  36.             case 1:{               
  37.                 /** Supongamos que tenemos la clase Objeto y dos clases que heredan de ésta: Tipo1 y Tipo2.*/             
  38.                
  39.                 /** Es posible que en vez de crear directamente algo tipo Objeto, tengamos que crearlo
  40.                  * a partir de una clase que hereda de objeto. En ese caso usamos un switch como el siguiente
  41.                  * ANTES de crear objetoNuevo*/
  42.                
  43.                 /** Primero, declaramos la variable que indicará el nombre de nuestro objeto y le damos un valor inicial*/
  44.                 Objeto nuevoObjeto = null;
  45.                
  46.                
  47.                
  48.                 /** El while sirve para verificar que se ingresó una opción correcta.*/
  49.                 while(nuevoObjeto==null){
  50.                    
  51.                     /** Ahora le pediremos al usuario que indique qué tipo de objeto desea crear*/
  52.                     // System.out.println("Elija el tipo de objeto");
  53.                     // System.out.println("1) Objeto del tipo 1"); // Ejemplo: Trabajador a honorario
  54.                     // System.out.println("2) Objeto del tipo 2"); // Ejemplo: Trabajador a plazo fijo
  55.                     int tipoDeObjeto = Leer.datoInt();
  56.  
  57.                     /** Hacemos un switch sobre la opción que eligió el usuario */
  58.                     switch(tipoDeObjeto){
  59.  
  60.                     case 1:{
  61.                         /** Pedimos al usuario los datos necesarios para crear un objeto tipo 1 */
  62.                         // int precio = Leer.datoInt();
  63.                         // String nombre = Leer.dato();
  64.                         // double estatura = Leer.datoDouble();
  65.  
  66.                         /** Creamos el objeto usando los parámetros de la clase Tipo1 (la cual hereda de Objeto) */                   
  67.                         // Objeto nuevoObjeto = new Tipo1(precio,nombre,estatura);
  68.                     }break;
  69.  
  70.                     case 2:{
  71.                         /** Pedimos al usuario los datos necesarios para crear un objeto tipo 2 */
  72.                         // int precio = Leer.datoInt();
  73.                         // String nombre = Leer.dato();
  74.                         // double estatura = Leer.datoDouble();
  75.                         // double peso = Leer.datoDouble();
  76.                         // String fechaNacimiento = Leer.dato();
  77.  
  78.                         /** Creamos el objeto usando los parámetros de la clase Tipo2 (la cual hereda de Objeto) */                   
  79.                         // Objeto nuevoObjeto = new Tipo2(precio,nombre,estatura,peso,fechaNacimiento);                
  80.                     }break;
  81.                     }
  82.  
  83.                     /**Si llegado a este punto, el objeto todavía es null, significa que el usuario ingresó
  84.                      * una opción que no era ni "1" ni "2" y por lo tanto no se entró a ningún caso del switch.
  85.                      * En tal caso, volveremos al inicio del while*/
  86.                     if(nuevoObjeto==null){
  87.                         System.out.println("Elija una opción válida");
  88.                     }
  89.  
  90.                 } /**Justo aquí termina el while(objeto==null)*/
  91.                                
  92.                 /** Saliendo del while, el objeto ya fue creado*/
  93.                
  94.                 /** Ahora, verificamos que no haya duplicados llamando al método revisarSiHayDuplicados.
  95.                  * Este métdodo recibe un ArrayList y un Objeto. Si hay un duplicado del objeto en el ArrayList
  96.                  * devuelve true. En caso contrario, false. */
  97.                 boolean hayDuplicados = revisarSiHayDuplicados(miArrayList , nuevoObjeto);
  98.                
  99.                 /** Si es que no hay duplicados, metemos el objeto en el ArrayList */
  100.                 if( !hayDuplicados ){
  101.                     miArrayList.add( nuevoObjeto );
  102.                     System.out.println("Se agregó exitosamente el objeto");                   
  103.                 }
  104.                 /**En caso contrario, le indicamos al usuario*/
  105.                 else{
  106.                     System.out.println("Se trató de ingresar, pero se encontró duplicado.");
  107.                 }              
  108.                    
  109.                
  110.                
  111.             }break;
  112.             /****************************************/
  113.             /**   FIN DEL CASO 1: INGRESAR OBJETO  **/
  114.             /****************************************/
  115.            
  116.            
  117.            
  118.            
  119.             /****************************************/
  120.             /** INICIO DEL CASO 2: BUSCAR OBJETO   **/
  121.             /****************************************/         
  122.             case 2:{
  123.                
  124.                 /** Pedimos al usuario que ingrese el identificador*/
  125.                 System.out.println("Ingrese identificador");
  126.                
  127.                 /**Si el identificador es un int*/
  128.                 int id = Leer.datoInt();
  129.                
  130.                 /**Si es un string */
  131.                 // String id = Leer.dato();
  132.                
  133.                 /** Buscamos el objeto por su identificador*/
  134.                 Objeto encontrado = null;
  135.                 for(int i=0; i<miArrayList.size();i++){
  136.                    
  137.                     /** Si el identificador es un int ...*/
  138.                     if( miArrayList.get(i).getIDENTIFICADOR()  == id ){
  139.                         encontrado = miArrayList.get(i);
  140.                     }
  141.                    
  142.                     /**Si el id es un string...*/
  143.                     //  if( miArrayList.get(i).getIDENTIFICADOR().equals(id) ){
  144.                     //  encontrado = miArrayList.get(i);
  145.                     //  }
  146.                    
  147.                 }
  148.                 /** Si al salir del for, "encontrado todavía es null, significa que no lo encontramos*/
  149.                 if( encontrado == null ){
  150.                     System.out.println("Objeto no encontrado");
  151.                 }
  152.                 /**En caso contrario, mostramos los datos del objeto */
  153.                 else{
  154.                    
  155.                 // System.out.println(" Nombre: "+encontrado.getNombre() );
  156.                 // System.out.println(" Precio: "+encontrado.gePrecio() );
  157.                 // etc...
  158.                
  159.                 }
  160.                
  161.                
  162.                
  163.                            
  164.             }break;
  165.  
  166.             /****************************************/
  167.             /**   FIN DEL CASO 2: BUSCAR OBJETO    **/
  168.             /****************************************/
  169.            
  170.            
  171.  
  172.  
  173.             /***********************************************************/
  174.             /**   INICIO DEL CASO 3: BUSCAR POR UNA CARACTERÍSTICA    **/
  175.             /***********************************************************/
  176.             case 3:{
  177.                 /** En general, estos hay que verlos caso a caso. De todos modos a continuación
  178.                  * pondremos el siguiente ejemplo:
  179.                  *  
  180.                  *  "Buscar el objeto del Tipo1 que tenga el mayor precio y mostrar sus datos"*/
  181.                
  182.                
  183.                 /**Primero hacemos las variables que almacenarán dichos datos*/
  184.                 int mayorPrecio = 0;
  185.                 String nombre = "Ninguno";
  186.                 double estatura = 0;
  187.                
  188.                 /**Hacemos un for que recorre todo el arreglo*/
  189.                 for(int i=0; i<miArrayList.size();i++){
  190.                    
  191.                     /**Si es que el objeto actual es del Tipo1*/
  192.                     if( miArrayList.get(i) instanceof Tipo1){
  193.                        
  194.                         /** Si es que el precio del objeto actual es mayor
  195.                          * al más grande que hayamos visto hasta ahora, lo reemplazamos */
  196.                         int precioActual = miArrayList.get(i).getPrecio();
  197.                         if( precioActual > mayorPrecio){
  198.                             mayorPrecio = precioActual;
  199.                             nombre = miArrayList.get(i).getNombre();
  200.                             estatura = miArrayList.get(i).getEstatura();                           
  201.                         }
  202.                        
  203.                     }                  
  204.                 }
  205.                
  206.                 /**Saliendo del for mostramos los datos */
  207.                 System.out.println("Datos:");
  208.                 System.out.println("Precio más alto:" +mayorPrecio);
  209.                 System.out.println("Nombre:"+nombre);
  210.                 System.out.println("Estatura:"+estatura);
  211.                
  212.                
  213.                
  214.             }break;
  215.             /***********************************************************/
  216.             /**   FIN DEL CASO 3: BUSCAR POR UNA CARACTERÍSTICA       **/
  217.             /***********************************************************/
  218.            
  219.  
  220.            
  221.            
  222.             /****************************************************************/
  223.             /**   INICIO DEL CASO 4: USAR TODOS LOS ELEMENTOS PARA ALGO    **/
  224.             /****************************************************************/     
  225.             case 4:{
  226.                
  227.                 /** Al igual que el caso 3, aquí se ve caso a caso */
  228.                
  229.                 /** A modo de ejemplo, mostremos el total de la suma
  230.                  * de todos los pesos de los objetos del Tipo2 */
  231.                
  232.                 /**Primero creamos la variable*/
  233.                 double totalPeso = 0;
  234.                
  235.                 /**El típico for */
  236.                 for(int i=0 ; i<miArrayList.size() ; i++){
  237.                    
  238.                     /**Si el objeto actual es del Tipo2, sumamos su peso */
  239.                     if( miArrayList.get(i)   instanceof   Tipo2){
  240.                        
  241.                         /** Hacemos un casteo porque solamente los objetos Tipo2 tienen
  242.                          * el método getPeso() */
  243.                        
  244.                         totalPeso = totalPeso + ((Tipo2) miArrayList.get(i)).getPeso();
  245.                        
  246.                     }
  247.                    
  248.                 }
  249.                
  250.                 System.out.println("El total es "+totalPeso);
  251.                
  252.                
  253.                
  254.                
  255.             }break;
  256.             /****************************************************************/
  257.             /**   FIN DEL CASO 4: USAR TODOS LOS ELEMENTOS PARA ALGO       **/
  258.             /****************************************************************/     
  259.            
  260.            
  261.            
  262.             case 5:{
  263.                 salir = true;
  264.             }break;
  265.            
  266.             }
  267.            
  268.            
  269.            
  270.            
  271.         }
  272.         System.out.println("Adiós!");     
  273.        
  274.        
  275.        
  276.     }
  277.    
  278.     public static boolean revisarSiHayDuplicados( ArrayList<Objeto> unArrayList , Objeto unObjeto ){
  279.        
  280.         for(int i=0; i<unArrayList.size(); i++){           
  281.            
  282.             /** Si el identificador es un número...*/
  283.             if( unArrayList.get(i).getIDENTIFICADOR()  ==  unObjeto.getIDENTIFICADOR() ){
  284.                 return true;               
  285.             }          
  286.            
  287.             /** En cambio, si el identificador es un String... */
  288.             // if( unArrayList.get(i).getIDENTIFICADOR() .equals(  unObjeto.getIDENTIFICADOR() ) ){
  289.             //  return true;
  290.             // }           
  291.         }
  292.        
  293.         /** En cualquier caso, si salimos del for significa que no hay duplicados */
  294.         return false;      
  295.        
  296.     }
  297.  
  298. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement