Ejercicios de Programación Tema 7. Programación Orientada a Objetos

Documentos relacionados
Tema 7.- Fundamentos de la Programación Orientada a Objetos

Resumen de Ficheros en Java. FileOutputStream(String nombre_fichero, boolean añadir)

Universidad de Cantabria

Parte I: Programación en un lenguaje orientado a objetos

Serialización de Objetos en Java. Dra. Maricela Bravo

Unidad Didáctica 2. Elementos básicos del lenguaje Java Tipos, declaraciones, expresiones y asignaciones

Examen. Programación II

Estructuras de control selectivas

Práctica 5. Fecha límite de entrega: viernes, 14 de diciembre

Unidad Didáctica 3. Tipos genéricos. Fundamentos de Programación Departamento de Lenguajes y Sistemas Informáticos

Prueba N o 1. Programación II

Variables. Una variable no es más que un nombre simbólico que identifica una dirección de memoria: vs.

Persistencia y Serialización en Java con Archivos

Entrada y Salida con Java

Tipos DataInputStream/DataOutputStream: L/E de datos de tipo simple y Cadenas (Strings) ObjectInputStream/ObjectOutputStream: para persistencia de obj

Centro Asociado Palma de Mallorca. Antonio Rivero Cuesta

Estructura de datos y Programación

1. Cuántas sentencias hay en la secuencia principal del siguiente programa?

Introducción a Java LSUB. 30 de enero de 2013 GSYC

Prácticas de Programación

Carlos Montenegro. Programación Orientada a Objetos Proyecto Curricular de Ingeniería de Sistemas

Programación Orientada a Objetos. Tema 7: Persistencia

Excepciones y E/S Java y Servicios Web I Master en Ingeniería Matemática

Qué es Java? Un lenguaje de programación Un entorno de desarrollo Un entorno de aplicación Un entorno de despliegue Es similar en sintaxis de C + +.

Examen de Prácticas de Programación Ingeniería Informática

HOJA DE EJERCICIOS 5 PROGRAMACIÓN CON EXCEPCIONES EN JAVA

Introducción a Java 10/02/2011. Tokens. Juan Manuel Fernández Peña Curso Rev Tokens. Tokens

PROGRAMACIÓN ORIENTADA A OBJETOS

PROGRAMACIÓN ORIENTADA A OBJETOS. Java se parece mucho a C pero sin todo lo que nos traía problemas.

PROGRAMACIÓN ORIENTADA A OBJETOS 10/02/2009. Examen de Java. Nombre: DNI: Titulación:

o Una clase es un tipo al cual pertenecen objetos o instancias de la clase.

PROGRAMACIÓN ORIENTADA A OBJETOS

Examen escrito de Programación 1

JAVA 1. Introducción

Examen escrito de Programación 1

Ejercicios de evaluación de fundamentos de programación en Java

CURSO : Programacion Java DOCENTE : ING. JUAN ZEVALLOS VALLE

EXAMEN PROGRAMACIÓN 21 de Septiembre de 2007 INGENIERÍA INFORMÁTICA Primera parte: Cuestiones 1,5 horas

/) 0! () 5!2 /)( 1! "!"# 2 ()/ $% $!" !! " #!!!$!!% &!!' ' ' "! ()()/ & $!" ()()(' (!(

Programa-Me 2011 Cómo resolver los problemas de Programa-Me

Java Básico. Métodos estáticos

Algoritmos y Estructuras de Datos Iteradores. Guillermo Román Díez

Parte I: Programación en un lenguaje orientado a objetos

CLAVE EXAMEN: a cd. c u r s o r = c u r s o r. g e t S i g u i e n t e ( ) ; p o s i c i o n ++;

Curso de Java Introducción a la Programación II

Bloque II. Elementos del lenguaje de programación Java

Curso de Java orientado a Android Parte 4

import java.applet.*; import java.awt.*; import java.awt.event.*;

Entrada y Salida de datos

Centro Asociado Palma de Mallorca. Antonio Rivero Cuesta

Práctica #5: Uso de control de flujo, Excepciones y Lectura Estándar

HERENCIA. Problema: Reparar el el coche. Jesús (Valencia) Luis, Mecánico (Valencia) Antonio, Servicio Técnico Ferrari (Madrid)

Arreglos de objetos y ArrayList. Archivos en Java Transversal Programación Orientada a Objetos Proyecto Curricular de Ingeniería de Sistemas

James Gosling, creador de Java

IIC1103 Introducción a la Programación. Ayudantía: Archivos

CURSO : ESTRUCTURA DE DATOS DOCENTE : ING. JUAN ZEVALLOS VALLE

Sebastián García Galán

Arreglos. H. Tejeda. Marzo Declaración de arreglos Inicialización de arreglos Uso de subíndices variables en un arreglo 5

GOBIERNO DEL PRINCIPADO DE ASTURIAS VICECONSEJERÍA DE PRESUPUESTOS Y ADMINISTRACIÓN PÚBLICA

Java. Introducción a la Programación Orientada a Objetos

Identificadores, palabras reservadas, tipos de datos, operadores aritméticos y el sistema estándar de salida en Java

Entrada y salida de datos. Entrada y salida de datos. Flujos estándar. Flujos estándar. Operación y flujos estándar en java

Concurso: Cuánto sabes de JAVA?

Guía - Taller # 2 (JAVA)

Introducción a Java (II) Dr. (c) Noé Alejandro Castro Sánchez

Práctica No. 5. Estructuras con Memoria Dinámica

Nota: en el directorio de prácticas y en PoliformaT puedes descargar los ficheros de código fuente de los ejemplos que aparecen en este anexo.

Elementos léxicos del lenguaje de programación Java

3.3 Conceptos Básicos del Lenguaje Java

IMPLEMENTACIÓN DE PILAS CON LISTAS EN C++

EXAMEN PROGRAMACIÓN 21 de Septiembre de 2007 INGENIERÍA INFORMÁTICA Primera parte: Cuestiones 1,5 horas

Tema: Grafos en C#. Objetivos Específicos. Materiales y Equipo. Introducción Teórica. Programación IV. Guía 7

TEMA 3. Árboles. Objetivos. Contenidos. Bibliografía. Básica

Bloque II. Elementos del lenguaje de programación Java

Construcciones del Lenguaje Java

Centro Asociado Palma de Mallorca. Antonio Rivero Cuesta

Unidad II. Fundamentos de programación en Java. Ing. José Luis Llamas Cárdenas

Guia#11: Tema: Estructuras en C#.

OBJETIVOS ÍNDICE BIBLIOGRAFÍA

VARIABLES, CONSTANTES Y EXPRESIONES ASIGNACIÓN. TIPOS ELEMENTALES. PRECEDENCIA DE LOS ESTRUCTURAS DE CONTROL. CONDICIONAL E

Introducción a Java LSUB. 15 de enero de 2015 GSYC

Manejo de errores: Excepciones en Java. ELO329: Diseño y Programación Orientados a Objetos

Depto. Ingeniería de Sistemas Telemáticos Universidad Politécnica de Madrid ETSI Telecomunicación Fundamentos de Programación 15 de diciembre de 2011

Ficheros de acceso aleatorio

Tema: Arreglos de Objetos en C++.

Instrucción de selección múltiple switch.

Programación Java. Introducción a Archivos de datos de Entrada

JAVA - Serializacíon / RMI. (C) Philippe Roose , 2005

Resumen Clase Anterior Ejercicio Clase 16 Archivos Ejemplo. ING1310 Introducción a la Computación. Archivos

Implementación del nivel de datos usando db4o

Centro Asociado Palma de Mallorca. Antonio Rivero Cuesta

Examen de Métodos de Programación Ingeniería Informática Primera Parte

2. Estructura de un programa en Java

NIVEL 15: ESTRUCTURAS RECURSIVAS BINARIAS

Tema 15: Aserciones 0

Curso de Java Introducción a la Programación I

Universidad Autónoma de Tlaxcala. M.C. José Juan Hernández Mora. Primera Sesión

Ingeniería del Software Separación entre Presentación y Lógica del Negocio

LISTAS ENLAZADAS DOBLES C++

PROGRAMACIÓN EN JAVA

Transcripción:

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