Ejercicios de Programación Tema 7. Programación Orientada a Objetos 22 de diciembre de 2013 1. Haz una clase llamada Agenda para manejar una agenda de teléfonos. Los objetos instanciados a partir de esa clase tendrán la siguiente funcionalidad: Construir una agenda a partir de un número máximo de contactos posibles (constructor) Añadir un contacto nuevo Listar todos los contactos de la agenda Buscar un contacto por nombre Buscar un contacto a partir de un número de teléfono Borrar un teléfono dado un nombre Modificar un número de telefono dado un nombre Puedes añadir más métodos si lo consideras adecuado. Las entradas de la agenda se modelarán mediante objetos de la clase Contacto que habrá que crear. Para cada Contacto de la agenda se almacenará la siguiente información: Nombre Dirección Código Postal Teléfono Puedes añadir los métodos que consideres adecuados. Para probar tus clases hay que escribir un programa TestAgenda.java donde se instacie un objeto de la clase Agenda y mediante un menú se pueda probar sus funcionalidades. En el menú se tiene que dar también la posibilidad de leer y escribir la agenda desde un fichero binario, pidiendo el nombre y de crear una nueva agenda. Trucos: Recuerda que para guardar un objeto usando WriteObject, el objeto, y todos los objetos que use el primero, han de ser serializable. Para ello has de añadir a la cabecera de la classe implements Serializable. Por ej. public class NombreDeLaClase implements Serializable { 1
Solución 2. Clase Contacto: 1 import java. i o. ; 2 3 public class Contacto implements S e r i a l i z a b l e { 4 // Atributos 5 S t r i n g nombre ; 6 S t r i n g d i r e c c i o n ; 7 int c o d i g o P o s t a l ; 8 int t e l e f o n o ; 9 10 // Metodos 11 public Contacto ( S t r i n g nombre, S t r i n g d i r e c c i o n, int codigopostal, int t e l e f o n o ) { 12 this. nombre = nombre ; 13 this. d i r e c c i o n = d i r e c c i o n ; 14 this. c o d i g o P o s t a l = c o d i g o P o s t a l ; 15 this. t e l e f o n o = t e l e f o n o ; 16 } 17 public S t r i n g t o S t r i n g ( ) { 18 S t r i n g r e s=" Nombre: "+ nombre+ "\n" + " Direccion "+ d i r e c c i o n +"\n" +" Codigo postal: "+ c o d i g o P o s t a l+"\n"+" Telefono: "+t e l e f o n o +"\n" ; 19 return r e s ; 20 } 21 public S t r i n g getnombre ( ) { 22 return nombre ; 23 } 24 25 public int g e t T e l e f o n o ( ) { 26 return t e l e f o n o ; 27 } 28 29 public void s e t T e l e f o n o ( int t e l e f o n o ) { 30 this. t e l e f o n o=t e l e f o n o ; 31 } 32 } 2
3. Clase Agenda: 1 import java. i o. ; 2 3 public class Agenda implements S e r i a l i z a b l e { 4 // Atributos 5 Contacto [ ] c o n t a c t o s=null ; 6 7 // Metodos 8 public Agenda ( int maxcont ) { 9 c o n t a c t o s = new Contacto [ maxcont ] ; 10 } 11 12 public boolean anyadircontacto ( S t r i n g nombre, S t r i n g d i r e c c i o n, int codigopostal, int t e l e f o n o ) { 13 for ( int i = 0 ; i < c o n t a c t o s. length ; i ++) { 14 i f ( c o n t a c t o s [ i ] == null ) { // s i t i o l i b r e 15 c o n t a c t o s [ i ] = new Contacto ( nombre, d i r e c c i o n, codigopostal, t e l e f o n o ) ; 16 return true ; 17 } 18 } 19 return f a l s e ; 20 } 21 22 public S t r i n g t o S t r i n g ( ) { 23 S t r i n g r e s="" ; 24 int cont =1; 25 for ( int i = 0 ; i < c o n t a c t o s. length ; i ++) { 26 i f ( c o n t a c t o s [ i ]!= null ) { // contacto encontrado 27 r e s +="\ncontacto "+cont + "\n" + c o n t a c t o s [ i ]. t o S t r i n g ( ) ; 28 cont++; 29 } 30 } 31 return r e s ; 32 } 33 34 public Contacto buscarpornombre ( S t r i n g nombre ) { 35 for ( int i = 0 ; i < c o n t a c t o s. length ; i ++) { 36 i f ( c o n t a c t o s [ i ]!= null ) {// hay contacto 37 S t r i n g nom = c o n t a c t o s [ i ]. getnombre ( ) ; 38 i f (nom. e q u a l s ( nombre ) ) { // encontrado 39 return c o n t a c t o s [ i ] ; 40 } 41 } 42 } 43 return null ; 44 } 45 46 public Contacto buscarportelefono ( int t e l e f o n o ) { 47 for ( int i = 0 ; i < c o n t a c t o s. length ; i ++) { 48 i f ( c o n t a c t o s [ i ]!= null ) {// hay contacto 49 int t e l= c o n t a c t o s [ i ]. g e t T e l e f o n o ( ) ; 3
50 i f ( t e l == t e l e f o n o ) { // encontrado 51 return c o n t a c t o s [ i ] ; 52 } 53 } 54 } 55 return null ; 56 } 57 58 public boolean borrarpornombre ( S t r i n g nombre ) { 59 for ( int i = 0 ; i < c o n t a c t o s. length ; i ++) { 60 i f ( c o n t a c t o s [ i ]!= null ) {// hay contacto 61 S t r i n g nom = c o n t a c t o s [ i ]. getnombre ( ) ; 62 i f (nom. e q u a l s ( nombre ) ) { // encontrado 63 c o n t a c t o s [ i ]= null ; 64 return true ; 65 } 66 } 67 } 68 return f a l s e ; 69 } 70 71 public boolean modificarpornombre ( S t r i n g nombre, int nuevotelefono ) { 72 for ( int i = 0 ; i < c o n t a c t o s. length ; i ++) { 73 i f ( c o n t a c t o s [ i ]!= null ) {// hay contacto 74 S t r i n g nom = c o n t a c t o s [ i ]. getnombre ( ) ; 75 i f (nom. e q u a l s ( nombre ) ) { // encontrado 76 c o n t a c t o s [ i ]. s e t T e l e f o n o ( nuevotelefono ) ; 77 return true ; 78 } 79 } 80 } 81 return f a l s e ; 82 } 83 } 4
4. Programa de prueba: 1 import java. i o. ; 2 import java. u t i l. ; 3 4 public class TestAgenda { 5 static Scanner t e c = new Scanner ( System. in ). uselocale ( Locale. US) ; 6 static Agenda miagenda=null ; 7 8 public static void main ( S t r i n g [ ] args ) { 9 int op =0; 10 do { 11 op=menu ( ) ; 12 switch ( op ) { 13 case 1 : 14 System. out. p r i n t ( "Numero maximo de contactos? " ) ; 15 int maxcont = t e c. nextint ( ) ; 16 miagenda = new Agenda ( maxcont ) ; 17 break ; 18 case 2 : 19 { 20 System. out. p r i n t ( "Fichero a leer? " ) ; 21 S t r i n g nombrefich = t e c. nextline ( ) ; 22 i f ( l e e r ( nombrefich ) ) 23 System. out. p r i n t l n ( "Agenda leida" ) ; 24 } 25 break ; 26 case 3 : 27 { 28 System. out. p r i n t ( "Nombre? " ) ; 29 S t r i n g nombre = t e c. nextline ( ) ; 30 System. out. p r i n t ( "Direccion? " ) ; 31 S t r i n g d i r e c c i o n = t e c. nextline ( ) ; 32 System. out. p r i n t ( "Codigo postal? " ) ; 33 int c o d i g o P o s t a l = t e c. nextint ( ) ; 34 System. out. p r i n t ( "telefono? " ) ; 35 int t e l e f o n o = t e c. nextint ( ) ; 36 i f ( miagenda. anyadircontacto ( nombre, d i r e c c i o n, codigopostal, t e l e f o n o ) ) 37 System. out. p r i n t l n ( "Contacto anyadido" ) ; 38 else 39 System. out. p r i n t l n ( "No se ha podido realizar la operacion" ) ; 40 } 41 break ; 42 case 4 : 43 System. out. p r i n t l n ( "Listado de la agenda" ) ; 44 System. out. p r i n t l n ( miagenda ) ; 45 break ; 46 case 5 : 47 { 48 System. out. p r i n t ( "Nombre a buscar? " ) ; 49 S t r i n g nombre=t e c. nextline ( ) ; 50 Contacto c o n t=miagenda. buscarpornombre ( nombre ) ; 5
51 i f ( cont!= null ) 52 System. out. p r i n t l n ( cont ) ; 53 else 54 System. out. p r i n t l n ( "Contacto no encontrado" ) ; 55 } 56 break ; 57 case 6 : 58 { 59 System. out. p r i n t ( "Telefono a buscar? " ) ; 60 int t e l e f o n o=t e c. nextint ( ) ; 61 Contacto cont=miagenda. buscarportelefono ( t e l e f o n o ) ; 62 i f ( cont!= null ) 63 System. out. p r i n t l n ( cont ) ; 64 else 65 System. out. p r i n t l n ( "Contacto no encontrado" ) ; 66 } 67 break ; 68 case 7 : 69 { 70 System. out. p r i n t ( "Nombre a borrar? " ) ; 71 S t r i n g nombre=t e c. nextline ( ) ; 72 i f ( miagenda. borrarpornombre ( nombre ) ) 73 System. out. p r i n t l n ( "Contacto borrado" ) ; 74 else 75 System. out. p r i n t l n ( "Contacto no encontrado" ) ; 76 } 77 break ; 78 case 8 : 79 { 80 System. out. p r i n t l n ( "Nombre a buscar? " ) ; 81 S t r i n g nombre = t e c. nextline ( ) ; 82 System. out. p r i n t ( "Nuevo telefono? " ) ; 83 int t e l e f o n o = t e c. nextint ( ) ; 84 i f ( miagenda. modificarpornombre ( nombre, t e l e f o n o ) ) 85 System. out. p r i n t l n ( "Telefono cambiado" ) ; 86 else 87 System. out. p r i n t l n ( "No se encontro el contacto " ) ; 88 } 89 break ; 90 case 9 : 91 { 92 System. out. p r i n t ( "Nombre del fichero destino? " ) ; 93 S t r i n g nombrefichero = t e c. nextline ( ) ; 94 i f ( guardar ( nombrefichero ) ) 95 System. out. p r i n t l n ( "Hecho" ) ; 96 else 97 System. out. p r i n t l n ( "Problemas escribiendo el fichero" ) ; 98 } 99 break ; 100 case 0 : 101 System. out. p r i n t l n ( "BYE! " ) ; 6
102 break ; 103 default : System. out. p r i n t l n ( "Opcion incorrecta" ) ; 104 } 105 106 }while ( op!=0) ; 107 } 108 109 public static int menu ( ) { 110 System. out. p r i n t l n ( "" ) ; 111 112 System. out. p r i n t l n ( "1.- Crear una agenda nueva" ) ; 113 System. out. p r i n t l n ( "2.- Leer agenda desde fichero" ) ; 114 System. out. p r i n t l n ( "3.- Anyadir contacto" ) ; 115 System. out. p r i n t l n ( "4.- Listar agenda" ) ; 116 System. out. p r i n t l n ( "5.- Buscar un contacto por nombre" ) ; 117 System. out. p r i n t l n ( "6.- Buscar un contacto por telefono" ) ; 118 System. out. p r i n t l n ( "7.- Borrar un contacto por nombre" ) ; 119 System. out. p r i n t l n ( "8.- Modificar un telefono por nombre" ) ; 120 System. out. p r i n t l n ( "9.- Guardar la agenda en un fichero" ) ; 121 System. out. p r i n t l n ( "0.- SALIR" ) ; 122 123 System. out. p r i n t l n ( "\telige opcion?" ) ; 124 int op = t e c. nextint ( ) ; 125 t e c. nextline ( ) ; // para e v i t a r e l problema con e l \n f i n a l 126 return op ; 127 } 128 129 130 public static boolean guardar ( S t r i n g nombrefichero ) { 131 try { 132 ObjectOutputStream f i c h = new ObjectOutputStream (new FileOutputStream ( nombrefichero ) ) ; 133 f i c h. writeobject ( miagenda ) ; 134 f i c h. c l o s e ( ) ; 135 return true ; 136 } catch ( FileNotFoundException e ) { 137 System. out. p r i n t ( "El fichero \""+nombrefichero+"\" no puede crearse" ) ; 138 return f a l s e ; 139 } catch ( IOException e ) { 140 System. out. p r i n t ( "El fichero\""+nombrefichero+"\" no puede crearse" ) ; 141 return f a l s e ; 142 } 143 } 144 145 public static boolean l e e r ( S t r i n g nombrefichero ) { 146 try { 147 ObjectInputStream f i c h = new ObjectInputStream (new FileInputStream ( nombrefichero ) ) ; 148 miagenda=(agenda ) f i c h. readobject ( ) ; 149 f i c h. c l o s e ( ) ; 150 return true ; 151 } catch ( FileNotFoundException e ) { 7
152 System. out. p r i n t l n ( "El fichero \""+nombrefichero+"\" no puede crearse" ) ; 153 return f a l s e ; 154 } catch ( IOException e ) { 155 System. out. p r i n t l n ( "Problemas escribiendo el fichero\""+ nombrefichero+"\"" ) ; 156 return f a l s e ; 157 } catch ( ClassNotFoundException e ) { 158 System. out. p r i n t l n ( "Problemas escribiendo el fichero \""+ nombrefichero+"\"" ) ; 159 return f a l s e ; 160 } 161 } 162 } Piensa: para qué se han puesto los parentesis en algunos case? 8