lunes, 19 de septiembre de 2011

Secuencia de imágenes con JavaScript

Dado el siguiente código en JavaScript, correspondiente a una secuencia de imágenes:

var SecuenciaID = null
var imagen = 0
var duracion = 1000
	
{imagenes = new CreaArray(4)
imagenes[1].src = "img/g1.jpg"
imagenes[2].src = "img/g2.png"
imagenes[3].src = "img/g3.jpg"
imagenes[4].src = "img/g4.jpg"
}
		
function CreaArray(n) {
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = new Image()
	}
	return this
}
		
function MostrarSecuencia() {
	{
		document.images["secuencia"].src = imagenes[imagen].src
		imagen++
		if ( imagen == 5 )
			imagen = 1
	}
	SecuenciaID = setTimeout("MostrarSecuencia()", duracion)
	SecuenciaEjecutandose = true
}
		
function IniciarSecuencia() {
	imagen = 1
	MostrarSecuencia()
}

Realizar los siguientes ejercicios:
  1. Conseguir que se muestre la secuencia de imágenes.
  2. Hacer que el tiempo durante el cual se muestra cada imagen sea distinto.
  3. Modificar el tamaño de cada imagen.
  4. Añadir música de fondo (debe estar sonando continuamente).
  5. Hacer que cuando termine la música de fondo, se pare la secuencia de imágenes.
  6. Añadir botones que inicien o paren la secuencia.
NOTA: en los cuatro primero ejercicios, el código JavaScript se añadió directamente dentro del código HTML, pero en los dos últimos, se creó un fichero por separado al que se referenciaba desde la cabecera del HTML.

EJERCICIO 1

<html>
	<script language="javascript" type="text/javascript">
		
		var SecuenciaID = null
		var imagen = 0
		var duracion = 1000
		
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		function CreaArray(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function MostrarSecuencia() {
			{
				document.images["secuencia"].src = imagenes[imagen].src
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion)
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
	</body>
</html>

EJERCICIO 2

<html>
	<script language="javascript" type="text/javascript">
		<!-- DECLARACIÓN DE VARIABLES -->
		var SecuenciaID = null
		var imagen = 0
		var tiempo = 1
		
		<!-- ARRAY DE IMÁGENES -->
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		<!-- ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen -->
		{duracion = new CreaArray2(4)
		duracion[1] = 1000
		duracion[2] = 2000
		duracion[3] = 3000
		duracion[4] = 4000
		}
		
		<!-- FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS -->
		function CreaArray(n) {
			<!-- DEFINIMOS EL TAMAÑO DEL ARRAY -->
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function CreaArray2(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = 0
			}
			return this
		}
		
		function MostrarSecuencia() {
			{
				<!-- A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia" -->
				<!-- LE ASIGNAMOS LAS DEL ARRAY -->
				document.images["secuencia"].src = imagenes[imagen].src
				<!-- INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA -->
				<!-- SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO. -->
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			<!-- setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO. -->
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			tiempo++
			if ( tiempo == 5 )
				tiempo = 1
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
	</body>
</html>

EJERCICIO 3

<html>
	<script language="javascript" type="text/javascript">
		<!-- DECLARACIÓN DE VARIABLES -->
		var SecuenciaID = null
		var imagen = 0
		var tiempo = 1
		
		<!-- ARRAY DE IMÁGENES -->
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		<!-- ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen -->
		{duracion = new CreaArray2(4)
		duracion[1] = 1000
		duracion[2] = 2000
		duracion[3] = 3000
		duracion[4] = 4000
		}
		
		<!-- ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen -->
		{size = new CreaArray2(4)
		size[1] = 100
		size[2] = 200
		size[3] = 300
		size[4] = 400
		}
		
		<!-- FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS -->
		function CreaArray(n) {
			<!-- DEFINIMOS EL TAMAÑO DEL ARRAY -->
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function CreaArray2(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = 0
			}
			return this
		}
		
		function MostrarSecuencia () {
			{
				<!-- DEFINIR TAMAÑO DE LAS IMÁGENES -->
				document.images["secuencia"].width = size[imagen]
				document.images["secuencia"].height = size[imagen]
				
				<!-- A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia" -->
				<!-- LE ASIGNAMOS LAS DEL ARRAY -->
				document.images["secuencia"].src = imagenes[imagen].src
				<!-- INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA -->
				<!-- SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO. -->
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			<!-- setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO. -->
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			tiempo++
				if ( tiempo == 5 )
					tiempo = 1
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
	</body>
</html>

EJERCICIO 4

<html>
	<script language="javascript" type="text/javascript">
		<!-- DECLARACIÓN DE VARIABLES -->
		var SecuenciaID = null
		var imagen = 0
		var tiempo = 1
		
		<!-- ARRAY DE IMÁGENES -->
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		<!-- ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen -->
		{duracion = new CreaArray2(4)
		duracion[1] = 1000
		duracion[2] = 2000
		duracion[3] = 3000
		duracion[4] = 4000
		}
		
		<!-- ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen -->
		{size = new CreaArray2(4)
		size[1] = 100
		size[2] = 200
		size[3] = 300
		size[4] = 400
		}
		
		<!-- FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS -->
		function CreaArray(n) {
			<!-- DEFINIMOS EL TAMAÑO DEL ARRAY -->
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function CreaArray2(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = 0
			}
			return this
		}
		
		function MostrarSecuencia () {
			{
				<!-- DEFINIR TAMAÑO DE LAS IMÁGENES -->
				document.images["secuencia"].width = size[imagen]
				document.images["secuencia"].height = size[imagen]
				
				<!-- A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia" -->
				<!-- LE ASIGNAMOS LAS DEL ARRAY -->
				document.images["secuencia"].src = imagenes[imagen].src
				<!-- INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA -->
				<!-- SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO. -->
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			<!-- setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO. -->
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			tiempo++
				if ( tiempo == 5 )
					tiempo = 1
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<div id="1">
			<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
		</div>
		<div id="2" style="position:absolute; top:300;">
			<EMBED src="sound/summer.mp3" autostart="true" loop="true">
		</div>
	</body>
</html>

EJERCICIO 5

Fichero .js
//DECLARACIÓN DE VARIABLES
var SecuenciaID = null
var imagen = 0
var tiempo = 1
var cancion = 0
		
//ARRAY DE IMÁGENES
{imagenes = new CreaArray(4)
imagenes[1].src = "img/g1.jpg"
imagenes[2].src = "img/g2.png"
imagenes[3].src = "img/g3.jpg"
imagenes[4].src = "img/g4.jpg"
}
		
//ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen
{duracion = new CreaArray2(4)
duracion[1] = 1000
duracion[2] = 2000
duracion[3] = 3000
duracion[4] = 4000
}
		
//ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen
{size = new CreaArray2(4)
size[1] = 100
size[2] = 200
size[3] = 300
size[4] = 400
}
		
//FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS
function CreaArray(n) {
	//DEFINIMOS EL TAMAÑO DEL ARRAY
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = new Image()
	}
	return this
}
		
function CreaArray2(n) {
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = 0
	}
	return this
}
		
function MostrarSecuencia () {
	{
	//DEFINIR TAMAÑO DE LAS IMÁGENES
	document.images["secuencia"].width = size[imagen]
	document.images["secuencia"].height = size[imagen]
		
	//A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia"
	//LE ASIGNAMOS LAS DEL ARRAY
	document.images["secuencia"].src = imagenes[imagen].src
	//INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA
	//SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO.
	imagen ++
		if ( imagen == 5 )
			imagen = 1
	}
				
	cancion = cancion + duracion[tiempo]
			
	if ( cancion <= 60000 ) {
		//setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO.
		SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			
		tiempo ++
			if ( tiempo == 5 )
				tiempo = 1
	}
}
		
function IniciarSecuencia() {
	imagen = 1
	MostrarSecuencia()
}

Fichero .html
<html>
	<head>
		<script src="js/secuencia.js" language="javascript" type="text/javascript">
		</script>
	</head>

	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
		<EMBED src="sound/summer.mp3" autostart="true" loop="false" hidden="yes">

	</body>
</html>

EJERCICIO 6

Fichero .js
//DECLARACIÓN DE VARIABLES
var SecuenciaID = null
var SecuenciaEjecutandose = null
var imagen = 1
//Inicialmente imagen vale 1 y eliminamos la función IniciarSecuencia
var tiempo = 1
		
//ARRAY DE IMÁGENES
{imagenes = new CreaArray(4)
imagenes[1].src = "img/g1.jpg"
imagenes[2].src = "img/g2.png"
imagenes[3].src = "img/g3.jpg"
imagenes[4].src = "img/g4.jpg"
}
	
//ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen
{duracion = new CreaArray2(4)
duracion[1] = 1000
duracion[2] = 2000
duracion[3] = 3000
duracion[4] = 4000
}
		
//ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen
{size = new CreaArray2(4)
size[1] = 100
size[2] = 200
size[3] = 300
size[4] = 400
}
		
//FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS
function CreaArray(n) {
	//DEFINIMOS EL TAMAÑO DEL ARRAY
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = new Image()
	}
	return this
}
		
function CreaArray2(n) {
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = 0
	}
	return this
}
		
function MostrarSecuencia () {
	if ( SecuenciaEjecutandose == true ) {
		//DEFINIR TAMAÑO DE LAS IMÁGENES
		document.images["secuencia"].width = size[imagen]
		document.images["secuencia"].height = size[imagen]
				
		//A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia"
		//LE ASIGNAMOS LAS DEL ARRAY
		document.images["secuencia"].src = imagenes[imagen].src
		//INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA
		//SIGUIENTE. SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO.
		imagen ++
		if ( imagen == 5 )
			imagen = 1
				
	//setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO.
	SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
		
	tiempo ++
	if ( tiempo == 5 )
		tiempo = 1
	}
			
}
		
function Iniciar () {
	SecuenciaEjecutandose = true
	MostrarSecuencia()
}
	
function Parar () {
	SecuenciaEjecutandose = false
	MostrarSecuencia()
}

Fichero .html
<html>
	<head>
		<script src="js/secuenciaConBotones.js" language="javascript" type="text/javascript">
		</script>
	</head>
	
	<body>
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
		<EMBED src="sound/summer.mp3" autostart="true" loop="true" hidden="yes">
		<input type="button" value="Iniciar secuencia" onClick="Iniciar()" style="position:absolute; left:500; top:50">
		<input type="button" value="Parar secuencia" onClick="Parar()" style="position:absolute; left:500; top:150">
	</body>
</html>

sábado, 17 de septiembre de 2011

Práctica HTML

Realizar una práctica libre de HTML utilizando distintas etiquetas y modificadores.
En mi caso cree una página con algunas de mis canciones favoritas, con imágenes, enlaces, etc. Además, en la parte superior de la página coloqué una tabla para practicar con las opciones que ofrece esta etiqueta.

<html>
	<head>
		<title>
			Mi m&#250sica favorita
		</title>
	</head>
	<body bgcolor="#E0F8F7" text="#04B4AE" link="#000000" vlink="#424242">
		<!--CABECERA-->
		<a name=top>
		<h1 align="center">MI M&#218SICA FAVORITA</h1>
		<hr color="#04B4AE" align="center" size="7" width="100%">
		
		<!--DESCRIPCIÓN DE MI PÁGINA WEB-->
		<div align="center">Esta p&#225gina contiene informaci&#243n sobre algunas de mis canciones favoritas.</div>
		
		<!--MENÚ-->
		<h3 align="center">CANCIONES:</h3>
		<table border="4" align="center" valign="middle" cellpadding="20">
			<tr>
				<td align="center" valign="middle">
					<a href="#cancion1">1.- BARROWLAND BALLROOM (Amy Macdonald)</a><br><br>
					<a href="#cancion2">2.- YELLOW (Coldplay)</a><br><br>
					<a href="#cancion3">3.- PARACHUTE (Cheryl Cole)</a>
				</td>
			</tr>
		</table>
		<br>
		<hr color="#04B4AE" align="center" size="5" width="100%">
		</a>
		
		<!--CANCIÓN 1-->
		<a name=cancion1>
		<h3><font color="#FF8000">1.- BARROWLAND BALLROOM</font></h3>
		<h4><font color="#FF8000"><u>Amy Macdonald</u></font></h4>
		<img src="http://pionerosonline.es/catalog/images/amy%20mcdonald%20this%20is%20ths%20life.jpg" alt="Car&#225tula This is the life" align="left" hspace="10">
		<pre><font color="#DF7401" size="+1" face="Arial"><b>Disco:</b> This is the life
<b>Letra:</b>
<p align="center"><i>Oh the lights outside they're as bright as the sun
They're much brighter than anyone.
Oh the girls in the queue, yes they're waiting for you...</i></p>
Si quieres ver la letra entera <a href="http://www.azlyrics.com/lyrics/amymacdonald/barrowlandballroom.html">HAZ CLIC AQU&#205</a>
<b>Videoclip:</b><a href="http://www.youtube.com/watch?v=K93FvHxzdlk"><img src="http://www.milbits.com/archivos/youtube-logo.jpg" alt="YouTube" align="middle" hspace="10" height="60"></a>
<p align="center"><i><blink><u>Nota:</u> La canci&#243n no tiene v&#237deo oficial.</blink></i></p>
<b>P&#225gina web oficial:</b> <a href="http://www.amymacdonald.co.uk/gb/home/">HAZ CLIC AQU&#205</a>
		</font>
		</pre>
		<div align="center"><a href="#top"><b>VOLVER AL INICIO</b></a></div>
		</a>
		<hr color="#000000" align="center" size="5" width="80%">
		
		<!--CANCIÓN 2-->
		<a name=cancion2>
		<h3 align="left"><font color="#D7DF01">2.- YELLOW</font></h3>
		<h4 align="left"><font color="#D7DF01"><u>Coldplay</u></font></h4>
		<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLsw-CHnE3MqezyBctmaZ6_XvKoBmUyEy19ubuc95-6g7njVbBMJelaF1zDZlfFG1MQMMattSHUJvLFrrsAdKxf_oEKVR4t3w6oY_xLzuCKzW7JEjDCL-tNuG2VxHbVP5y98styHi-NfKS/s400/coldplay-parachutes.jpg" alt="Car&#225tula Parachutes" align="right" hspace="10" height="350">
		<pre><font color="#868A08" size="+1" face="Arial"><b>Disco:</b> Parachutes
<b>Letra:</b>
<p align="center"><i>Look at the stars,
Look how they shine for you,
And everything you do...</i></p>
Si quieres ver la letra entera <a href="http://www.azlyrics.com/lyrics/coldplay/yellow.html">HAZ CLIC AQU&#205</a>
<b>Videoclip:</b><a href="http://www.youtube.com/watch?v=1MwjX4dG72s"><img src="http://www.milbits.com/archivos/youtube-logo.jpg" alt="YouTube" align="middle" hspace="10" height="60"></a>
<p align="center"><i><blink><u>Nota:</u> V&#237deo oficial.</blink></i></p>
<b>P&#225gina web oficial:</b> <a href="http://www.coldplay.com/">HAZ CLIC AQU&#205</a>
		</font>
		</pre>
		<div align="center"><a href="#top"><b>VOLVER AL INICIO</b></a></div>
		</a>
		<hr color="#000000" align="center" size="5" width="80%">
		
		<!--CANCIÓN 3-->
		<a name=cancion3>
		<h3><font color="#01DF01">3.- PARACHUTE</font></h3>
		<h4><font color="#01DF01"><u>Cheryl Cole</u></font></h4>
		<img src="http://strictly-cheryl.tk/wp-content/uploads/2011/01/Cheryl-Cole-3-Words-album-cover.jpg" alt="Car&#225tula 3 Words" align="left" hspace="10" height="350">
		<pre><font color="#088A08" size="+1" face="Arial"><b>Disco:</b> 3 Words
<b>Letra:</b>
<p align="center"><i>I don't tell anyone about the way you hold my hand
I don't tell anyone about the things that we have planned
Won't tell anybody, won't tell anybody...</i></p>
Si quieres ver la letra entera <a href="http://www.azlyrics.com/lyrics/cherylcole/parachute.html">HAZ CLIC AQU&#205</a>
<b>Videoclip:</b><a href="http://www.youtube.com/watch?v=-AWoZmAxKxg"><img src="http://www.milbits.com/archivos/youtube-logo.jpg" alt="YouTube" align="middle" hspace="10" height="60"></a>
<p align="center"><i><blink><u>Nota:</u> V&#237deo oficial.</blink></i></p>
<b>P&#225gina web oficial:</b> <a href="http://www.cherylcole.com/">HAZ CLIC AQU&#205</a>
		</font>
		</pre>
		<div align="center"><a href="#top"><b>VOLVER AL INICIO</b></a></div>
		</a>
		<hr color="#000000" align="center" size="5" width="80%">
		
	</body>
</html>

lunes, 12 de septiembre de 2011

Imágenes, textos y capas en HTML

Para empezar a conocer HTML, realizamos varias prácticas que consistían en utilizar las distintas etiquetas, añadiendo sus modificadores, etc. Muchas de estás prácticas eran progresivas, es decir, sobre la misma práctica se iban modificando cosas hasta tener el resultado final.

La primera práctica consiste en colocar varias imágenes y modificar su estilo.

<html>
	<head>
		<title>PR&#193CTICA 1</title>
	</head>
	<body>
		<h2 align="center">Pr&#225ctica 1</h2>
		<hr align="center" size="10" width="80%" color="blue">
		<img src="chrome.jpg" alt="Tama&#241o original" border="3">
		<img src="firefox.png" alt="Achatada" border="0" height="300" width="600">
		<img src="explorer.jpg" alt="Alargada" border="0" height="600" width="300">
		<img src="opera.png" alt="Doble grande" border="0" height="600">
	</body>
</html>

1ª MODIFICACIÓN
Es buena práctica almacenar las imágenes, sonidos, vídeo, etc. en un directorio aparte, para que las rutas sean más claras y lo tengamos todo organizado.
Esta modificación consiste en crear un directorio para las imágenes, guardar éstas en él y modificar lo que sea necesario para que se siga viendo correctamente.

<html>
	<head>
		<title>PR&#193CTICA 1.1: IM&#193GENES EN DIRECTORIOS</title>
	</head>
	<body>
		<h2 align="center">Pr&#225ctica 1.1</h2>
		<hr align="center" size="10" width="80%" color="blue">
		<img src="img/chrome.jpg" alt="Tama&#241o original" border="3">
		<img src="img/firefox.png" alt="Achatada" border="0" height="300" width="600">
		<img src="img/explorer.jpg" alt="Alargada" border="0" height="600" width="300">
		<img src="img/opera.png" alt="Doble grande" border="0" height="600">
	</body>
</html>

2ª MODIFICACIÓN
Añadir texto con distintos modificadores (color, cursiva, negrita, etc.). Además, poner enlaces en las imágenes para que dirijan a la web que queramos.

<html>
	<head>
		<title>PR&#193CTICA 1.2: CON TEXTOS</title>
	</head>
	<body>
		<h2 align="center">Pr&#225ctica 1.2</h2>
		<hr align="center" size="10" width="80%" color="blue"> 
		<marquee><s>Texto en marquesina y tachado.</s></marquee>
		<!-- Al ponerlo en marquesina, se pone directamente encima de la imagen -->
		<a href="http://www.google.com/chrome?hl=es"><img src="img/chrome.jpg" alt="Tama&#241o original" border="3"></a>
		<b><i>Texto en negrita y cursiva.</i></b>
		<a href="http://www.mozilla-europe.org/es/"><img src="img/firefox.png" alt="Achatada" border="0" height="300" width="600" align="top"></a>
		<blink><font color="blue">Texto parpadeante y azul.</font></blink>
		<a href="http://windows.microsoft.com/es-ES/windows/downloads?T1=downloadsIE"><img src="img/explorer.jpg" alt="Alargada" border="0" height="600" width="300" align="middle"></a>
		Texto sin marcadores.
		<a href="http://www.opera.com/browser/download/"><img src="img/opera.png" alt="Doble grande" border="0" height="600" align="bottom"></a>
	</body>
</html>

3ª MODIFICACIÓN
Crear distintas capas que contengan las distintas partes de la página que hemos estado haciendo.

<html>
	<head>
		<title>PR&#193CTICA 1.3: CON CAPAS</title>
	</head>
	<body>
		<div name="capa_inicio">
		<h2 align="center">Pr&#225ctica 1.3</h2>
		<hr align="center" size="10" width="80%" color="blue"> 
		</div>
		
		<div name="capa_imagen1">
		<marquee><s>Texto en marquesina y tachado.</s></marquee>
		<a href="http://www.google.com/chrome?hl=es"><img src="img/chrome.jpg" alt="Tama&#241o original" border="3"></a>
		</div>
		
		<div name="capa_imagen2">
		<b><i>Texto en negrita y cursiva.</i></b>
		<a href="http://www.mozilla-europe.org/es/"><img src="img/firefox.png" alt="Achatada" border="0" height="300" width="600" align="top"></a>
		</div>
		
		<div name="capa_imagen3">
		<blink><font color="blue">Texto parpadeante y azul.</font></blink>
		<a href="http://windows.microsoft.com/es-ES/windows/downloads?T1=downloadsIE"><img src="img/explorer.jpg" alt="Alargada" border="0" height="600" width="300" align="middle"></a>
		</div>
		
		<div name="capa_imagen4">
		Texto sin marcadores.
		<a href="http://www.opera.com/browser/download/"><img src="img/opera.png" alt="Doble grande" border="0" height="600" align="bottom"></a>
		</div>
	</body>
</html>

4ª MODIFICACIÓN
Añadir estilos a las capas.

<html>
	<head>
		<title>PR&#193CTICA 1.4: CON CAPAS (OPCIONAL)</title>
	</head>
	<body>
		<div name="capa_inicio" style="position:absolute; left:100; top:100;
		visibility:hidden; background-color:#66CCFF">
		<h2 align="center">Pr&#225ctica 1.4</h2>
		<hr align="center" size="10" width="80%" color="blue"> 
		</div>
		
		<div name="capa_imagen1" style="position:absolute; left:20; top:20; width:200px;
		height:200px; overflow:scroll">
		<marquee><s>Texto en marquesina y tachado.</s></marquee>
		<a href="http://www.google.com/chrome?hl=es"><img src="img/chrome.jpg" alt="Tama&#241o original" border="3"></a>
		</div>
		
		<div name="capa_imagen2" style="position:absolute; left:300; top:20; width:400px;
		height:200px; background-color:#FF6600; overflow:hidden">
		<b><i>Texto en negrita y cursiva.</i></b>
		<a href="http://www.mozilla-europe.org/es/"><img src="img/firefox.png" alt="Achatada" border="0" height="300" width="600" align="top"></a>
		</div>
		
		<div name="capa_imagen3" style="position:absolute; left:400; top:280; width:300px;
		height:600px; overflow:auto">
		<blink><font color="blue">Texto parpadeante y azul.</font></blink>
		<a href="http://windows.microsoft.com/es-ES/windows/downloads?T1=downloadsIE"><img src="img/explorer.jpg" alt="Alargada" border="0" height="600" width="300" align="middle"></a>
		</div>
		
		<div name="capa_imagen4" style="position:absolute; left:10; top:900; width:900px;
		height:700px; background-image:url(http://hd-wallpaper.org/wallpapers/10/Color_Flow_Light_Effect.jpg)">
		Texto sin marcadores.
		<a href="http://www.opera.com/browser/download/"><img src="img/opera.png" alt="Doble grande" border="0" height="600" align="bottom"></a>
		</div>
	</body>
</html>

La etiqueta del salto de línea <br> no me la coge dentro del código, así que la he eliminado. Simplemente la utilizaba para separar un poco unas imágenes de otras.

viernes, 9 de septiembre de 2011

Ejercicio con cuadrados

Supón que tenemos un fichero de texto que contiene la descripción de una serie de figuras y que se ajusta al siguiente formato.
  • 1ª línea...      <nombre de la clase de figura>
  • siguientes líneas...      <datos de la figura, uno por línea>
Ejemplo:
  • Circulo
  • 20
  • 120
  • 30
  • Cuadrado
  • 23
  • 0
  • 50
  • ...
Implementa un programa que lea dicho fichero atendiendo solo a los cuadrados y a sus datos.
Por cada cuadrado deberá crear un objeto cuadrado según la descripción y guardarlo serializado en un fichero binario llamado soloCuadrados.dat

public class EjercicioCuadrados {
    public static void main (String [] args) throws IOException {
        FileReader fr = new FileReader("figuras.txt");
        BufferedReader br = new BufferedReader(fr);
        FileOutputStream fos = new FileOutputStream("soloCuadrados.dat");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        int coorX, coorY, lado;
        String aux;
        aux = br.readLine();
        while (aux != null) {
            if (aux.equals("Cuadrado")) {
                coorX = Integer.parseInt(br.readLine());
                coorY = Integer.parseInt(br.readLine());
                lado = Integer.parseInt(br.readLine());
                oos.writeObject(new Cuadrado(coorX, coorY, lado));
            }
            aux = br.readLine();
        }
        oos.close();
        fos.close();
        br.close();
        fr.close();
    }
}

Ejercicio con figuras

En este ejercicio se utilizan las figuras creadas anteriormente. Se fabricarán varias figuras, que se almacenarán en un fichero utilizando la clase ObjectOutputStream, que nos permite serializar objetos (para ello la clase figura debe implementar Serializable).
Posteriormente se recuperarán las figuras y calcularemos el área media.

public class GuardarFiguras3 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //FABRICAR VARIAS FIGURAS Y GUARDARLAS EN UN FICHERO
        FileOutputStream fos = new FileOutputStream("figuras3");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        LinkedList listado = new LinkedList();
        ListIterator it = listado.listIterator();
        Figura aux;
        float sup=0;
        it.add(new Rectangulo(1, 3, 5, 6));
        sup+=it.previous().area();
        it.next();
        it.add(new Coche(3, 2, 6, 9));
        sup+=it.previous().area();
        it.next();
        it.add(new Circulo(4, 4, 4));
        sup+=it.previous().area();
        it.next();
        it.add(new Rectangulo(1, 3, 5, 5));
        sup+=it.previous().area();
        it.next();
        it.add(new Triangulo(2, 4, 3, 4, 5));
        sup+=it.previous().area();
        sup = sup/5;
        System.out.println("Área media inicial: "+sup);
        ListIterator it2 = listado.listIterator();
        while (it2.hasNext()) {
            oos.writeObject(it2.next());
        }
        oos.close();
        fos.close();
        //RECUPERAR FIGURAS Y CALCULAR LA MEDIA (DEBE COINCIDIR CON LA INICIAL)
        FileInputStream fis = new FileInputStream("figuras3");
        ObjectInputStream ois = new ObjectInputStream(fis);
        float media = 0;
        int contador = 0;
        try {
            while (true) {
                aux = (Figura) ois.readObject();
                media += aux.area();
                contador++;
            }
        } catch (EOFException e) {
        }
        ois.close();
        fis.close();
        media = media / contador;
        System.out.println("Área media final: " + media);
    }
}

Ejercicio "Figuras geométricas"

Este ejercicio lo realizamos a lo largo de varias semanas, añadiendo funciones, creando clases nuevas y realizando algunos ejercicios con las figuras que se añadirán en entradas posteriores.

Dada la clase abstracta* "Figura", añadirle varias funciones de desplazamiento, una función que permita consultar su posición y dos funciones que permitan modificar directamente las coordenadas.

public abstract class Figura implements Serializable {
    protected  Point posicion;
    public Figura(int a, int b) {
    posicion= new Point(a,b);}
    public abstract float area();
    public abstract float perimetro();
    public abstract int alto();
    public abstract int ancho();
    public abstract void dibujar(Graphics g);
    public abstract void guardar(OutputStream out) throws IOException;
    public abstract void cargar(InputStream in) throws IOException;
    public void arr(int incremento){
        this.posicion.y -= incremento;
    }
    public void abj(int incremento){
        this.posicion.y += incremento;
    }
    public void izq(int incremento){
        this.posicion.x -= incremento;
    }
    public void der(int incremento){
        this.posicion.x += incremento;
    }
    public Point posicion(){
        Point aux = new Point(posicion);
        return aux;
    }
    public void set_y(int pos_y){
        this.posicion.y = pos_y;
    }
    public void set_x(int pos_x){
        this.posicion.x = pos_x;
    }
}

Crear la clase (excepción) "FiguraFormatException", que hereda de "IllegalArgumentException" y se lanzará si en la función Cargar, se lee del flujo una figura que no es la indicada.

public class FiguraFormatException extends IllegalArgumentException{
    public FiguraFormatException() {
    }
    public FiguraFormatException(String string) {
        super(string);
    }
}

Dadas las clases "Triangulo", "Elipse", "Circulo", "Rectangulo" y "Cuadrado", que heredan de la clase abstracta "Figura", añadir un constructor que reciba un InputStream, que tendrá los datos adecuados para inicializar la figura. Además, se sobreescribirán las funciones abstractas de la clase "Figura".

CLASE Triangulo

public class Triangulo extends Figura {
    protected int lado1, lado2, lado3;
    private int lx, altura;
    public Triangulo(int a, int b, int c, int d, int e) {
        super(a, b);
        int elMayor = (c > d & c > e) ? c : ((d > e) ? d : e);
        if (elMayor >= (c + d + e - elMayor)) {
            throw new IllegalArgumentException("Los lados del triangulo son imposibles");
        }
        lado1 = c;
        lado2 = d;
        lado3 = e;
        lx = (lado2 * lado2 - lado3 * lado3 - lado1 * lado1) / (2 * lado1);
        altura = (int) Math.sqrt(lado3 * lado3 - lx * lx);
    }
    public Triangulo(InputStream in) throws IOException {
        super(0, 0);
        cargar(in);
    }
    public void guardar(OutputStream out) throws IOException {
        DataOutputStream escribir = new DataOutputStream(out);
        escribir.writeUTF("figuras.Triangulo");
        escribir.writeInt(posicion.x);
        escribir.writeInt(posicion.y);
        escribir.writeInt(lado1);
        escribir.writeInt(lado2);
        escribir.writeInt(lado3);
        escribir.flush();
    }
    public void cargar(InputStream in) throws IOException {
        DataInputStream leer = new DataInputStream(in);
        String figura;
        figura = leer.readUTF();
        if (!figura.equals("figuras.Triangulo")) {
            throw new FiguraFormatException();
        }
        posicion.x = leer.readInt();
        posicion.y = leer.readInt();
        lado1 = leer.readInt();
        lado2 = leer.readInt();
        lado3 = leer.readInt();
        lx = (lado2 * lado2 - lado3 * lado3 - lado1 * lado1) / (2 * lado1);
        altura = (int) Math.sqrt(lado3 * lado3 - lx * lx);
    }
    public float area() {
        return (lado1 * altura) / 2;
    }
    public float perimetro() {
        return lado1 + lado2 + lado3;
    }
    public int alto() {
        return altura;
    }
    public int ancho() {
        return lado1;
    }
    public void dibujar(Graphics g) {
        Color cActual = g.getColor();
        int[] xPuntos = {posicion.x,
            posicion.x + lado1,
            posicion.x + lado1 + lx};
        int[] yPuntos = {posicion.y,
            posicion.y,
            posicion.y + altura};
        g.fillPolygon(xPuntos, yPuntos, 3);
        g.setColor(Color.white);
        g.drawPolygon(xPuntos, yPuntos, 3);
        g.setColor(cActual);
    }
}

CLASE Elipse

public class Elipse extends Figura {
    public final static float PI = 3.1415F;
    protected int dMenor, dMayor;
    public Elipse(int a, int b, int c, int d) {
        super(a, b);
        dMenor = c;
        dMayor = d;
    }
    public Elipse(InputStream in) throws IOException {
        super(0, 0);
        this.cargar(in);
    }
    public void guardar(OutputStream out) throws IOException {
        DataOutputStream escribir = new DataOutputStream(out);
        escribir.writeUTF("figuras.Elipse");
        escribir.writeInt(posicion.x);
        escribir.writeInt(posicion.y);
        escribir.writeInt(dMenor);
        escribir.writeInt(dMayor);
        escribir.flush();
    }
    public void cargar(InputStream in) throws IOException {
        DataInputStream leer = new DataInputStream(in);
        if (!leer.readUTF().equals("figuras.Elipse")) {
            throw new FiguraFormatException();
        }
        posicion.x = leer.readInt();
        posicion.y = leer.readInt();
        dMenor = leer.readInt();
        dMayor = leer.readInt();
    }
    public float area() {
        return PI * dMenor * dMayor;
    }
    public float perimetro() {
        return PI * (dMenor + dMayor);
    }
    public int alto() {
        return dMayor;
    }
    public int ancho() {
        return dMenor;
    }
    public void dibujar(Graphics g) {
        Color cActual = g.getColor();
        g.fillOval(posicion.x, posicion.y, dMenor, dMayor);
        g.setColor(Color.white);
        g.drawOval(posicion.x, posicion.y, dMenor, dMayor);
        g.setColor(cActual);
    }
}

CLASE Circulo

public class Circulo extends Elipse {
    public Circulo(int a, int b, int d) {
        super(a, b, d, d);
    }
    public Circulo(InputStream is) throws IOException {
        super(0, 0, 0, 0);
        //Si se produce una IOException, se borrarán los datos del objeto Circulo
        cargar(is);
    }
    @Override
    public void guardar(OutputStream os) throws IOException {
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF("figuras.Circulo");
        dos.writeInt(posicion.x);
        dos.writeInt(posicion.y);
        dos.writeInt(dMayor);
        dos.flush();
    }
    @Override
    public void cargar(InputStream is) throws IOException {
        DataInputStream dis = new DataInputStream(is);

        if (!dis.readUTF().equals("figuras.Circulo")) {
            throw new FiguraFormatException();
        }
        posicion = new Point(dis.readInt(), dis.readInt());
        dMayor = dis.readInt();
        dMenor = dMayor;
    }
}

CLASE Rectangulo

public class Rectangulo extends Figura {
    protected int lado1, lado2;
    public Rectangulo(int a,int b,int c,int d) {
        super(a,b);
        lado1=c;
        lado2=d; }
    public Rectangulo(InputStream in) throws IOException {
        super(0,0);
        this.cargar(in);
    }
    public float area() {
        return lado1*lado2;
    }
    public float perimetro() {
        return lado1*2+lado2*2;
    }
    public int alto() {
        return lado2;
    }
    public int ancho() {
        return lado1;
    }
    public void dibujar(Graphics g) {
        Color cActual=g.getColor();
        g.fillRect(posicion.x,posicion.y,lado1,lado2);
        g.setColor(Color.white);
        g.drawRect(posicion.x,posicion.y,lado1,lado2);
        g.setColor(cActual);
    }
    public void guardar (OutputStream out) throws IOException{
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeUTF("figuras.Rectangulo");
        dos.writeInt((int) super.posicion().getX());
        dos.writeInt((int) super.posicion().getY());
        dos.writeInt(lado1);
        dos.writeInt(lado2);
        dos.flush();
    }
    public void cargar (InputStream in) throws IOException{
        DataInputStream dis = new DataInputStream(in);
        if(!dis.readUTF().equals("figuras.Rectangulo")) {
            throw new FiguraFormatException("La figura no es un rectángulo.");
        }
        super.set_x(dis.readInt());
        super.set_y(dis.readInt());
        lado1=dis.readInt();
        lado2=dis.readInt();
    }
}

CLASE Cuadrado

public class Cuadrado extends Rectangulo {
    public Cuadrado(int a, int b, int c) {
        super(a, b, c, c);
    }
    public Cuadrado(InputStream in) throws IOException {
        super(0, 0, 0, 0);
        cargar(in);
    }
    @Override
    public void guardar(OutputStream out) throws IOException {
        DataOutputStream escribe = new DataOutputStream(out);
        escribe.writeUTF("figuras.Cuadrado");
        escribe.writeInt(posicion.x);
        escribe.writeInt(posicion.y);
        escribe.writeInt(this.alto());
        escribe.flush();
    }
    @Override
    public void cargar(InputStream in) throws IOException {
        DataInputStream lee = new DataInputStream(in);
        if (!lee.readUTF().equals("figuras.Cuadrado")) {
            throw new FiguraFormatException();
        }
        posicion.x = lee.readInt();
        posicion.y = lee.readInt();
        lado1 = lee.readInt();
        lado2 = lado1;
    }
}

Crear las clases "TEquilatero" que hereda de "Triangulo" y "Coche" que hereda de "Figura".

La clase "TEquilatero":
  • Es un triángulo con los tres lados iguales.

La clase "Coche":

  • Estará formada por dos círculos (ruedas) y un rectángulo.
  • Su posición la indicará la esquina superior izquierda.
  • Los círculos tendrán el mismo tamaño que la altura del rectángulo.
    • Si la suma de los dos diámetros es mayor a la longitud del rectángulo, entonces el diámetro será la mitad de la longitud.
CLASE TEquilatero

public class TEquilatero extends Triangulo {
    public TEquilatero(int a, int b, int c) {
        super(a, b, c, c, c);
    }
    public TEquilatero(InputStream in) throws IOException {
        super(0, 0, 0, 0, 0);
        cargar(in);
    }
    @Override
    public void cargar(InputStream into) throws IOException {
        DataInputStream di = new DataInputStream(into);
        if (!di.readUTF().equals("figuras.TEquilatero")) {
            throw new FiguraFormatException();
        }
        posicion.x = di.readInt();
        posicion.y = di.readInt();
        lado1 = di.readInt();
    }
    @Override
    public void guardar(OutputStream o) throws IOException {
        DataOutputStream out = new DataOutputStream(o);
        out.writeUTF("figuras.TEquilatero");
        out.writeInt(posicion.x);
        out.writeInt(posicion.y);
        out.writeInt(lado1);
        out.flush();
    }
}

CLASE Coche

public class Coche extends Figura {
    private Rectangulo chasis;
    private Circulo rueda1, rueda2;
    public Coche(int a, int b, int alto, int ancho) {
        super(a, b);
        if (alto <= ancho) {
            chasis = new Rectangulo(a, b, ancho, alto / 2);
            rueda1 = new Circulo(a, b + chasis.alto(), alto / 2);
            rueda2 = new Circulo(a + ancho - alto / 2, b + chasis.alto(), alto / 2);
        } else {
            chasis = new Rectangulo(a, b, ancho, alto - (ancho / 2));
            rueda1 = new Circulo(a, b + chasis.alto(), ancho / 2);
            rueda2 = new Circulo(a + ancho / 2, b + chasis.alto(), ancho / 2);
        }
    }
    public Coche(InputStream in)throws IOException{
        super(0,0);
        this.cargar(in);
    }
    @Override
    public float area() {
        return chasis.area() + rueda1.area() + rueda2.area();
    }
    @Override
    public float perimetro() {
        return chasis.perimetro() + rueda1.perimetro() + rueda2.perimetro();
    }
    @Override
    public int alto() {
        return chasis.alto() + rueda1.alto();
    }
    @Override
    public int ancho() {
        return chasis.ancho();
    }
    @Override
    public void dibujar(Graphics g) {
        chasis.dibujar(g);
        rueda1.dibujar(g);
        rueda2.dibujar(g);
    }
    @Override
    public void arr(int incremento) {
        super.arr(incremento);
        chasis.arr(incremento);
        rueda1.arr(incremento);
        rueda2.arr(incremento);
    }
    @Override
    public void abj(int incremento) {
        super.abj(incremento);
        chasis.abj(incremento);
        rueda1.abj(incremento);
        rueda2.abj(incremento);
    }
    @Override
    public void izq(int incremento) {
        super.izq(incremento);
        chasis.izq(incremento);
        rueda1.izq(incremento);
        rueda2.izq(incremento);
    }
    @Override
    public void der(int incremento) {
        super.der(incremento);
        chasis.der(incremento);
        rueda1.der(incremento);
        rueda2.der(incremento);
    }
    @Override
    public void set_y(int pos_y) {
        super.set_y(pos_y);
        chasis.set_y(pos_y);
        rueda1.set_y(pos_y + chasis.alto());
        rueda2.set_y(pos_y + chasis.alto());
    }
    @Override
    public void set_x(int pos_x) {
        super.set_x(pos_x);
        chasis.set_x(pos_x);
        rueda1.set_x(pos_x);
        rueda2.set_x(pos_x + chasis.ancho() - rueda2.ancho());
    }
    public void guardar(OutputStream out) throws IOException {
        DataOutputStream escribe = new DataOutputStream(out);
        escribe.writeUTF("figuras.Coche");
        escribe.writeInt(posicion.x);
        escribe.writeInt(posicion.y);
        escribe.flush();
        rueda1.guardar(out);
        rueda2.guardar(out);
        chasis.guardar(out);

    }
    public void cargar(InputStream in) throws IOException {
        DataInputStream leer = new DataInputStream(in);
        String clase;
        if (!(clase=leer.readUTF()).equals("figuras.Coche")) {
            throw new FiguraFormatException("La figura no es un coche. Se ha leído: "+clase);
        }
        posicion.x = (leer.readInt());
        posicion.y = (leer.readInt());
        rueda1 = new Circulo(in);
        rueda2 = new Circulo(in);
        chasis = new Rectangulo(in);
    }
}

* Una clase será abstracta cuando no queremos que se puedan crear objetos de esa clase. Sus funciones pueden ser abstractas, en este caso, las clases que hereden de una abstracta pueden sobreescribir esas funciones o dejarla abstracta (la clase hija será también abstracta). Una clase abstracta también puede tener funciones no abstractas, es decir, que tengan código.

miércoles, 7 de septiembre de 2011

Creación de fichero con datos aleatorios

Supongamos que disponemos de un fichero binario que contiene una secuencia de registros con la siguiente estructura:
  1. Altura. (float)
  2. Edad. (int)
  3. Repetidor. (boolean)
EJERCICIOS:
  • Haz una aplicación para generar un fichero con estas características de contenido aleatorio.
  • Haz otra que lo lea y calcule la edad media de los alumnos repetidores.
  • Y otra más que muestre el contenido del fichero correctamente tabulado para facilitar su legibilidad.
GENERACIÓN DEL FICHERO CON CONTENIDO ALEATORIO

public class Ejercicio2_escribir {
    public static void main (String [] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("registro2");
        DataOutputStream dos = new DataOutputStream(fos);
        int numRegistros = (int) (Math.random()*100+1);
        int i = 0, edad;
        double aux;
        float altura;
        boolean repetidor;
        while (i < numRegistros) {
            altura=(float) (Math.random()*2);
            altura=(int) (altura*100);
            altura=(float) (altura/100);
            dos.writeFloat(altura);
            edad=(int) (Math.random()*100+1);
            dos.writeInt(edad);
            aux=Math.random();
            if (aux < 0.5)
                repetidor=true;
            else
                repetidor=false;
            dos.writeBoolean(repetidor);
            i++;
        }
        dos.close();
        fos.close();
    }
}

LEER FICHERO Y CALCULAR EDAD MEDIA DE REPETIDORES

public class Ejercicio2_media {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("registro2");
        DataInputStream dis = new DataInputStream(fis);
        int suma=0, aux, contador = 0;
        float media;
        try {
            while (true) {
                dis.readFloat();
                aux=dis.readInt();
                if (dis.readBoolean()) {
                    suma+=aux;
                    contador++;
                }
            }
        }
        catch (EOFException e) {
        }
        fis.close();
        dis.close();
        if (contador==0) {
            System.out.println("No hay repetidores.");
        }
        else {
            media = (float) suma/contador;
            System.out.println("La edad media de los repetidores es: " +media+ " años.");
        }
    }
}

MOSTRAR EL CONTENIDO DEL FICHERO

public class Ejercicio2_mostrar {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("registro2");
        DataInputStream dis = new DataInputStream(fis);
        System.out.printf("ALTURA\tEDAD\tREPETIDOR");
        System.out.println();
        try {
            while (true) {
                System.out.printf("%.2f\t%2d\t%b", dis.readFloat(), dis.readInt(), dis.readBoolean());
                System.out.println();
            }
        }
        catch (EOFException e) {
        }
        fis.close();
        dis.close();
    }
}

martes, 6 de septiembre de 2011

Ejercicio creación de ficheros

Realizar un programa que cree un fichero con los siguientes datos:
  • 85.23, de tipo float.
  • 18, de tipo entero.
  • true, de tipo boolean.
Se realizarán dos versiones, en la primera el fichero será un fichero de texto, en el que se almacenarán caracteres. En la segunda versión el fichero será de tipo binario, es decir, se guardarán bytes.

public class EjercicioFlujo4 {
    public static void main (String [] arg) throws IOException{
        //VERSIÓN 1: fichero de texto
        FileWriter fich = new FileWriter("nuevo");
        PrintWriter impr = new PrintWriter(fich);
        impr.println(85.23F);
        impr.println(18);
        impr.println(true);
        impr.close();
        fich.close();

        //VERSIÓN 2: fichero binario
        FileOutputStream fich1 = new FileOutputStream("nuevo2");
        DataOutputStream impr1 = new DataOutputStream(fich1);
        impr1.writeFloat(85.23F);
        impr1.writeInt(18);
        impr1.writeBoolean(true);
        impr1.close();
        fich1.close();

        //LEER LOS FICHEROS
        //VERSIÓN 1: fichero de texto
        FileReader fich3 = new FileReader("nuevo");
        BufferedReader aux = new BufferedReader(fich3);
        System.out.println(Float.parseFloat(aux.readLine()));
        System.out.println(Integer.parseInt(aux.readLine()));
        System.out.println(Boolean.parseBoolean(aux.readLine()));
        aux.close();
        fich3.close();
        /*Otra forma
        FileInputStream fis = new FileInputStream("nuevo");
        Scanner entrada = new Scanner(fis);
        System.out.println(entrada.nextLine());
        System.out.println(entrada.nextInt());
        System.out.println(entrada.nextBoolean());
        entrada.close();
        fis.close();*/

        //VERSIÓN 2: fichero binario
        FileInputStream fich2 = new FileInputStream("nuevo2");
        DataInputStream leer = new DataInputStream(fich2);
        System.out.println(leer.readFloat());
        System.out.println(leer.readInt());
        System.out.println(leer.readBoolean());
        leer.close();
        fich2.close();        
    }
}

jueves, 1 de septiembre de 2011

Ejercicio función totaliza

Realizar la siguiente función:
  • static int totaliza (Reader in). Recibe un flujo de datos de tipo "Reader" y lee los números enteros que contiene. La función irá sumando estos números hasta tener el total, que es el dato que se retorna.
Si se produce error al leer alguna línea y pasarlo a entero, se atrapará la excepción y se sacará un mensaje con el número de la línea que no se ha leído.
Se añade el programa principal con el que se probó la función.

public class EjercicioFlujo3 {
    public static void main (String [] args) throws FileNotFoundException, IOException {
        String ruta="/home/veronica/Documentos/fichero";
        int total;
        FileReader leerFich = new FileReader(ruta);
        total=totaliza(leerFich);
        leerFich.close();
        System.out.println(total);
    }
    public static int totaliza (Reader in) throws IOException {
        int resultado=0;
        int linea=1;
        String num;
        BufferedReader aux = new BufferedReader(in);
        while ((num=aux.readLine()) != null) {
            try {
                resultado += Integer.parseInt(num);
            }
            catch(NumberFormatException e) {
                System.err.println("Fallo en la línea: "+linea);
            }
            linea++;
        }
        aux.close();
        return resultado;
    }
}

Ejercicio analizar String

Queremos analizar el juego de caracteres de un String, es decir, queremos saber cómo se almacena en memoria, conocer la secuencia de bytes. Para ello emplearemos las clases de Java que nos permiten trabajar con la entrada/salida de datos.

public class EjercicioFlujo {
    public static void main (String [] args) throws IOException {
        Scanner entrada = new Scanner(System.in);
        String p;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(baos);
        //Si quisiéramos guardarlo en Unicode16:
        //OutputStreamWriter osw = new OutputStreamWriter(baos, "UTF-16");
        byte[] resultado;
        p=entrada.nextLine();
        osw.write(p);
        osw.close();
        baos.close();
        resultado = baos.toByteArray();
        System.out.println(p);
        for (int i=0; i<resultado.length;i++){
            //Para conseguir que nos escriba el código de todos los caracteres
            System.out.println(0x00FF & (int)resultado[i]);
        }
    }
}

En este caso hemos utilizado las clases ByteArrayOutputStream y OutputStreamWriter.