Libro Java2 GMV
Libro Java2 GMV
NACIONAL DE
INGENIERIA
INTRODUCCION.............................................................................................................................................1
CAPITULO UNO..............................................................................................................................................3
GESTION DE EXCEPCIONES..................................................................................................................235
5.1. LAS EXCEPCIONES ESTÁNDAR............................................................................................235
5.1.1. Las excepciones.......................................................................................................................236
5.1.2. Captura de las excepciones.....................................................................................................238
5.1.3. Manejando varias excepciones...............................................................................................239
PAQUETES....................................................................................................................................................247
6.1. PAQUETES..................................................................................................................................247
6.1.1. La sentencia package (paquete)..............................................................................................248
6.1.2. Compilación de clases en paquetes........................................................................................248
6.1.3. La sentencia import.................................................................................................................250
6.1.4. Protección de accesos.............................................................................................................251
6.1.5. Los paquetes estándar.............................................................................................................253
6.2. EJEMPLOS DE USO DE PAQUETES.......................................................................................253
CAPITULO SIETE.......................................................................................................................................257
INTERFACES................................................................................................................................................257
7.1. ¿QUÉ ES UN INTERFACE?.......................................................................................................257
7.2. DIFERENCIAS ENTRE UN INTERFACE Y UNA CLASE ABSTRACTA...................................................258
7.3. LOS INTERFACES Y EL POLIMORFISMO..........................................................................................259
7.3.1. Herencia simple.......................................................................................................................260
7.3.2. Interfaces.................................................................................................................................261
CAPITULO OCHO.......................................................................................................................................267
APPLETS.......................................................................................................................................................313
9.1. DEFINICIÓN DE APPLET.........................................................................................................313
9.2. EL APPLET MÍNIMO.................................................................................................................314
9.3. EL PRIMER APPLET........................................................................................................................314
9.4. INSERTANDO UN APPLET EN UNA PÁGINA WEB.............................................................................316
9.5. FUNCIONES GRÁFICAS...........................................................................................................319
9.5.1. El contexto gráfico..................................................................................................................324
9.5.2. Establecer un color.................................................................................................................326
9.5.3. Dibujar una línea....................................................................................................................326
9.5.4. Dibujar un rectángulo.............................................................................................................326
9.5.5. Dibujar un arco.......................................................................................................................327
9.5.6. Dibujar un polígono................................................................................................................327
9.5.7. Dibujar una imagen................................................................................................................328
9.6. LAS CLASES COLOR, FONT Y FONTMETRICS................................................................................331
9.6.1. La clase Color.........................................................................................................................331
9.6.2. La clase Font...........................................................................................................................335
9.6.3. La clase FontMetrics..............................................................................................................336
9.7. INTERFAZ GRAFICA CON EL USUARIO (GUI) Y COMPONENTES BASICOS................344
9.7.1. COMPONENTES....................................................................................................................345
9.7.2. ROTULOS (Label)..................................................................................................................346
9.7.3. ADMINISTRADOR DE DISEÑOS GRIDLAYOUT.................................................................365
9.7.4. BOTONES PARA PULSAR (BUTTON)...................................................................................369
9.8. LOS GESTORES FLOWLAYOUT, BORDERLAYOUT Y GRIDLAYOUT...............................................375
9.8.1. El gestor FlowLayout..............................................................................................................375
9.8.2. El gestor BorderLayout...........................................................................................................377
9.8.3. El gestor GridLayout..............................................................................................................379
9.9. EL GESTOR DE DISEÑO GRIDBAGLAYOUT....................................................................................381
9.9.1. Ejemplo: diseño de una ficha..................................................................................................381
9.9.2. El panel...................................................................................................................................382
9.9.3. El applet..................................................................................................................................383
9.9.4. El gestor de diseño GridBagLayout........................................................................................384
9.9.5. Añadir los componentes al applet...........................................................................................384
CAPITULO DIEZ.........................................................................................................................................389
HILO Y SINCRONIZACIÓN......................................................................................................................389
iv Ing. Gilmer Matos Vila
10.1. EL MODELO DE HILO DE JAVA.......................................................................................................389
10.1.1. Prioridades de hilo.............................................................................................................390
10.1.2. Sincronización....................................................................................................................390
10.1.3. Intercambio de mensajes....................................................................................................391
10.2. THREAD........................................................................................................................................391
10.3. RUNNABLE....................................................................................................................................391
10.4. PRIORIDADES DE LOS HILOS..........................................................................................................393
10.5. SINCRONIZACIÓN..........................................................................................................................393
10.5.1. La sentencia synchronized..................................................................................................394
10.6. COMUNICACIÓN ENTRE HILOS......................................................................................................395
10.6.1. Bloqueos.............................................................................................................................396
10.7. RESUMEN DE LA INTERFAZ DE PROGRAMACIÓN (API) DE HILOS.................................................397
10.7.1. Métodos de clase................................................................................................................397
10.7.2. Métodos de instancia..........................................................................................................398
v
INTRODUCCION
c:\j2sdk1.4.0
c:\j2sdk1.4.0\bin
path=%path%;c:\jdk1.3\bin
c:\j2sdk1.4.0\lib
c:\j2sdk1.4.0\jre
c:\j2sdk1.4.0\jre\bin
c:\j2sdk1.4.0\jre\bin\classic
c:\j2sdk1.4.0\jre\bin\hotspot
c:\j2sdk1.4.0\jre\lib
c:\j2sdk1.4.0\jre\lib\ext
c:\j2sdk1.4.0\jre\lib\security
c:\j2sdk1.4.0\jre\lib\applet
c:\j2sdk1.4.0\src.jar
c:\j2sdk1.4.0\demo
c:\j2sdk1.4.0\demo\applets
c:\j2sdk1.4.0\demo\jfc
c:\j2sdk1.4.0\demo\jpda
c:\j2sdk1.4.0\demo\sound
c:\j2sdk1.4.0\include
c:\j2sdk1.4.0\include-old
Class . . .
. .
class programa1
{
/*
*/
/**
1.11. VARIABLES
Una variable es un ítem de datos nombrado por un
identificador. Debemos explícitamente suministrar un
nombre y un tipo para cada variable que quisiéramos
usar en nuestro programa. El nombre de la variable
debe ser un identificador válido --una serie de
caracteres Unicode que comienzan con una letra.
Utilizamos el nombre de la variable para referirnos al
dato que la variable contiene. El tipo de la variable
determina el conjunto de valores que se pueden
almacenar en esa variable y el tipo de operaciones que
se pueden realizar con ella. Para dar a una variable
un tipo y un nombre, escribimos una declaración de
variable, que en general se verá de la siguiente
forma:
tipo nombre;
o también:
Tipo Descripción
1.13. LITERALES
Un valor constante en Java se crea utilizando una
representación literal de él. Java utiliza cinco tipos
de elementos: enteros, reales en coma flotante,
booleanos, caracteres y cadenas, que se pueden poner
en cualquier lugar del código fuente de Java. Cada uno
de estos literales tiene un tipo correspondiente
asociado con él.
8864L Long
PROGRAMACION CON JAVA 2 19
37.266 Double
37.266D double
87.363F float
26.77e3 double
'c' char
true boolean
false boolean
"Hola" String
1.14. OPERADORES
Un operador realiza una función en uno, dos o tres
operandos. Un operador que requiere un solo operando
se denomina operador unario. Por ejemplo, ++ es un
operador unario que incrementa el valor de su operando
en 1. Un operador que requiere de dos operandos es un
operador binario. Por ejemplo, = es un operador
binario que asigna el valor del operando de la derecha
al operando de la izquierda. Y, finalmente, el
operador ternario el que requiere tres operandos. El
lenguaje de programación Java tiene un operador
ternario, ?:, que es un atajo de la sentencia ifelse,
el cual se analizará más adelante .
++ op++
Incrementa op en 1; se evalúa el valor de op antes de
ser incrementado
++ ++op
Incrementa op en 1; se evalúa el valor de op después
de ser incrementado
-- op--
Decrementa op en 1; se evalúa el valor de op antes de
ser decrementado
-- --op
Decrementa op en 1; se evalúa el valor de op después
de ser decrementado
&&
op1 && op1 y op2 son ambos true, evalúa condicionalmente
op2 op2
||
op1 || Cualquiera de op1 u op2 es true, evalúa
op2 condicionalmente op2
! ! op op es false
op1 &
&
op2 op1 y op2 son ambos true, siempre evalúa op1 y op2
|
op1 | Cualquiera de op1 u op2 es true, siempre evalúa op1
op2 y op2
^
op1 ^ Si op1 y op2 son diferentes. Esto es si uno u otro de
op2 los operandos es true, pero no ambos.
>>
op1 >> Corrimiento de bits de op1 hacia la derecha por la
op2 distancia de op2
<<
op1 << Corrimiento de bits de op1 hacia la izquierda por la
op2 distancia de op2
>>>
op1 >>> Corrimiento de bits de op1 hacia la derecha por la
op2 distancia de op2 (sin signo)
1.14.5. OPERADORES DE ASIGNACIÓN
[] tipo []
Declara un array de tamaño desconocido,
que contiene elementos tipo.
tipo[ op1 ]
Crea un array de op1 elementos. Debe ser
declarado con el operador new.
Instanceof
op1 instanceof Devuelve verdadero si op1 es una instancia
op2 de op2
Abrir el flujo
Abrir el flujo
Mientras haya más información
Mientras haya más información
leer la información
escribir información
cerrar el flujo
cerrar el flujo
Flujo sumidero de
datos
Flujo de
procesamiento
Variable = System.in.read()
System.out.write(parametro)
Ejemplo ( 0):
//archivo: lecturabytes.java
import java.io.*;
class lecturabytes
{
public static void main (String[] args)
throws IOException
{
// declaración de las variables
int n;
//lee un byte
n=System.in.read();
//escribe un byte
System.out.write(n);
//escribe un salto de línea
System.out.write('\n');
}
}
import java.io.*;
InputStream Reader
OutputStream Writer
bytes
caracteres
import java.io.*;
class lecturacadenas
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
Class Integer
Atributos
Static int MAX_VALUE
Una constante que contiene el máximo
valor en un int: 231-1.
Static int MIN_VALUE
Una constante que contiene el minimo
valor en un int: -231.
Constructores
Integer(int value)
Construye un objeto Integer que representa el
valor especifico del int.
Integer(String s)
Construye un objeto Integer que representa el
valor int indicado por el parámetro String.
1
Fuente: JDK HELP
PROGRAMACION CON JAVA 2 37
Métodos
byte byteValue()
Returns the value of this Integer as a
byte.
int compareTo(Integer anotherInteger)
Compares two Integer objects
numerically.
int compareTo(Object o)
Compares this Integer object to another
object.
static Integer decode(String nm)
Decodes a String into an Integer.
double doubleValue()
Returns the value of this Integer as a
double.
boolean equals(Object obj)
Compares this object to the specified
object.
float floatValue()
Returns the value of this Integer as a
float.
static Integer getInteger(String nm)
Determines the integer value of the
system property with the specified name.
static Integer getInteger(String nm, int val)
Determines the integer value of the
system property with the specified name.
static Integer getInteger(String nm, Integer val)
Returns the integer value of the
system property with the specified name.
int hashCode()
Returns a hash code for this Integer.
int intValue()
Returns the value of this Integer as an
int.
long longValue()
Returns the value of this Integer as a
long.
static int parseInt(String s)
Parses the string argument as a signed
decimal integer.
static int parseInt(String s, int radix)
38 Ing. Gilmer Matos Vila
Parses the string argument as a signed
integer in the radix specified by the second
argument.
short shortValue()
Returns the value of this Integer as a
short.
static String toBinaryString(int i)
Returns a string representation of the
integer argument as an unsigned integer in
base 2.
static String toHexString(int i)
Returns a string representation of the
integer argument as an unsigned integer in
base 16.
static String toOctalString(int i)
Returns a string representation of the
integer argument as an unsigned integer in
base 8.
String toString()
Returns a String object representing
this Integer's value.
static String toString(int i)
Returns a String object representing
the specified integer.
static String toString(int i, int radix)
Returns a string representation of the
first argument in the radix specified by the
second argument.
static Integer valueOf(String s)
Returns an Integer object holding the
value of the specified String.
static Integer valueOf(String s, int radix)
Returns an Integer object holding the
value extracted from the specified String when
parsed with the radix given by the second
argument.
Class Float
Atributos
static float MAX_VALUE
A constant holding the largest positive
finite value of type float.
static float MIN_VALUE
A constant holding the smallest positive
nonzero value of type float.
static float NaN
A constant holding a Not-a-Number (NaN)
value of type float.
static float NEGATIVE_INFINITY
A constant holding the negative infinity
of type float.
static float POSITIVE_INFINITY
A constant holding the positive infinity
of type float.
static Class TYPE
The Class instance representing the
primitive type float.
Constructores
Float(double value)
Constructs a newly allocated Float object that
represents the argument converted to type float.
Float(float value)
Constructs a newly allocated Float object that
represents the primitive float argument.
Float(String s)
Constructs a newly allocated Float object that
represents the floating-point value of type float represented
by the string.
2
Fuente: HELP JDK 2 Ver 1.4 (Idioma Original)
40 Ing. Gilmer Matos Vila
Métodos
byte byteValue()
Returns the value of this Float as a
byte (by casting to a byte).
static int compare(float f1, float f2)
Compares the two specified float
values.
int compareTo(Float anotherFloat)
Compares two Float objects numerically.
int compareTo(Object o)
Compares this Float object to another
object.
double doubleValue()
Returns the double value of this Float
object.
boolean equals(Object obj)
Compares this object against the
specified object.
static int floatToIntBits(float value)
Returns a representation of the
specified floating-point value according to the
IEEE 754 floating-point "single format" bit
layout.
static int floatToRawIntBits(float value)
Returns a representation of the
specified floating-point value according to the
IEEE 754 floating-point "single format" bit
layout, preserving Not-a-Number (NaN) values.
float floatValue()
Returns the float value of this Float
object.
int hashCode()
Returns a hash code for this Float
object.
static float intBitsToFloat(int bits)
Returns the float value corresponding
to a given bit represention.
int intValue()
Returns the value of this Float as an
int (by casting to type int).
boolean isInfinite()
Returns true if this Float value is
//archivo: lecturanumeros.java
import java.io.*;
//import java.lang.*;
class lecturanumeros
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
nume=Integer.parseInt(sdato);//convierte cadena a
// entero
nume=nume+5;
System.out.println("el numero + 5 es : "+nume);
numf=Float.parseFloat(sdato);//convierte cadena a
//float
numf=numf+5;
System.out.println("el numero + 5 es : "+numf);
}
}
import java.io.*;
class operarit
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada:
flujoE
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
Atributos
static double E
The double value that is closer than any
other to e, the base of the natural logarithms.
static double PI
The double value that is closer than any
other to pi, the ratio of the circumference of a
circle to its diameter.
Métodos
static double abs(double a)
Returns the absolute value of a double
value.
static float abs(float a)
Returns the absolute value of a float
value.
static int abs(int a)
Returns the absolute value of an int
value.
static long abs(long a)
Returns the absolute value of a long
value.
static double acos(double a)
Returns the arc cosine of an angle, in
the range of 0.0 through pi.
static double asin(double a)
Returns the arc sine of an angle, in
PROGRAMACION CON JAVA 2 45
the range of -pi/2 through pi/2.
static double atan(double a)
Returns the arc tangent of an angle, in
the range of -pi/2 through pi/2.
static double atan2(double y, double x)
Converts rectangular coordinates (x, y)
to polar (r, theta).
static double ceil(double a)
Returns the smallest (closest to
negative infinity) double value that is not less
than the argument and is equal to a mathematical
integer.
static double cos(double a)
Returns the trigonometric cosine of an
angle.
static double exp(double a)
Returns Euler's number e raised to the
power of a double value.
static double floor(double a)
Returns the largest (closest to
positive infinity) double value that is not
greater than the argument and is equal to a
mathematical integer.
static double IEEEremainder(double f1, double f2)
Computes the remainder operation on two
arguments as prescribed by the IEEE 754 standard.
static double log(double a)
Returns the natural logarithm (base e)
of a double value.
static double max(double a, double b)
Returns the greater of two double
values.
static flota max(float a, float b)
Returns the greater of two float values.
static int max(int a, int b)
Returns the greater of two int values.
static long max(long a, long b)
Returns the greater of two long values.
static double min(double a, double b)
Returns the smaller of two double
values.
static flota min(float a, float b)
(X,Y)
x r * cos
y r * sen
//archivo: cartepola.java
import java.io.*;
import java.lang.Math;
class cartepola
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
La salida es:
1.19.1. SENTENCIA if
Nos permite ejecutar una parte u otra del
código dependiendo de la evaluación.
La sintaxis es la siguiente:
if (expresión booleana) {
// bloque por true
sentencia v1;
sentencia v2;
...
sentencia vn;
}
else {
// bloque por false
sentencia f1;
sentencia f2;
...
sentencia fn;
}
expresión es una evaluación lógica, es decir,
debe evaluar true o false. Por true se
ejecuta el primer bloque de sentencias y por
false el segundo.
if (expresión booleana)
sentencia por true;
else
sentencia por false;
//archivo: valabsoluto.java
import java.io.*;
class valabsoluto
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
int num,valabs;
La salida será:
import java.io.*;
class valabsoluto2
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
int num;
import java.io.*;
class mayor
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
int n1,n2,n3;//numeros
int mayor;// número mayor
// calcular el mayor
if (n1>n2)
if (n1>n3)
mayor=n1;
else
mayor=n3;
else
if (n2>n3)
mayor=n2;
else
mayor=n3;
//archivo: division.java
import java.io.*;
class division
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
import java.io.*;
class sueldo
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
double su;//sueldo
char cat;//categoría
int ing;//año de ingreso
PROGRAMACION CON JAVA 2 59
// lectura de los 3 numeros
System.out.print("Ingrese sueldo : ");
sdato = flujoE.readLine(); // leer una línea de texto
su=Float.parseFloat(sdato);//convierte cadena a float
//
if (ing<1980)
{
if (cat=='a')
su=su*1.15;
if (cat=='b')
su=su*1.20;
if (cat=='c')
su=su*1.25;
}
else //en otro caso ing>=1980
{
if (cat=='a')
su=su*1.12;
if (cat=='b')
su=su*1.17;
if (cat=='c')
su=su*1.22;
}
import java.io.*;
System.out.println("Comision: "+comision);
}
}
Switch (expresion)
{
case expresión_constante_1:
[sentencia1;]
case expresión_constante_2:
[sentencia2;]
...
[default:]
sentencia n;
}
class vocales
{
public static void main (String[] args)
throws IOException
char c;//caracter
// lectura
System.out.print("Ingrese letra : ");
c=(char) System.in.read();//lee caracter
//convertir a mayusculas
c=Character.toUpperCase(c);
// verificar si es letra
if (Character.isLetter(c))
switch (c)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':System.out.println(c+" es vocal"); break;
default : System.out.println(c+" no es vocal");
}
else
System.out.println(c+" no es letra");
}
}
import java.io.*;
class mes
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
int mes;//mes
TIPO DE COSTO
TARIFA (U.M./Kw-h)
1 2.30
2 8.25
3 6.42
4 5.80
5 9.65
import java.io.*;
double consumo,tarifa,monto;
int tipo;
System.out.print("Consumo: ");
sdato = flujoE.readLine(); // leer una línea de texto
consumo=Float.parseFloat(sdato);//convierte cadena
if(tarifa!=0)
{
monto=consumo*tarifa;
System.out.println("\nMonto a pagar: "+monto);
}
else
System.out.println("\nTarifa incorrecta");
}
}
o bien:
sentencia;
1. Se evalúa la condición.
import java.io.*;
class divisores
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
s = s + r
import java.io.*;
PROGRAMACION CON JAVA 2 75
class sumacifras
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
}
}
Ejemplo:
class promposi
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lee numeros
n=0;
s=0;
while(num!=0)
{
if(num>0)
{ s=s+num;
n++;
}
}//fin de main
}//fin de la clase
Ejemplo:
a existe 1 vez(ces)
e existe 1 vez(ces)
class exa1p120032
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
int a=0,e=0,i=0,o=0,u=0,nv=0;//contadores
char car;
while(car!='*')
{
switch (car)
{
case 'a': a++;break;
case 'e': e++;break;
case 'i': i++;break;
case 'o': o++;break;
case 'u': u++;break;
default : nv++;
}
if(a>0)
System.out.println("a existe "+a+" vez(ces)");
if(e>0)
System.out.println("e existe "+e+" vez(ces)");
if(i>0)
System.out.println("i existe "+i+" vez(ces)");
if(o>0)
System.out.println("o existe "+o+" vez(ces)");
if(u>0)
System.out.println("u existe "+u+" vez(ces)");
if(nv>0)
System.out.println("caracteres que no son vocales
existen "+ nv+ " vez(ces)");
}//fin de main
}//fin de la clase
class exa1p220032
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
boolean c1=false,c2=false,c3=false,c4=false,c5=false;
int cif=0, e=0, s=0;//cif=cantidad de cifras, e=exponente
//s= acumulador
int num,base;//num=número en base 10, base=base mayor que
10
int r;
String sdato;
System.out.print("Ingrese numero en base 10: ");
sdato=flujoE.readLine();
num=Integer.parseInt(sdato);
while(num!=0)
{
r=num%base;
cif=cif+1;
if (r>=10)
{
switch (cif)
{
case 1: c1=true;break;
case 2: c2=true;break;
case 3: c3=true;break;
case 4: c4=true;break;
case 5: c5=true;break;
}//fin de switch
r=r-10;
}//fin de if
s=s+r*(int) Math.pow(10,e);
e=e+1;
num=num/base;
}//fin de whilw
System.out.print("\n");
}//fin de main
}//fin de la clase
do {
sentencia 1;
sentencia 2;
sentencia 3;
...
sentencia n;
}
while (expresión booleana);
o bien:
do
sentencia 1;
while (expresión booleana);
2 3 4 5 6 7 8
S 1 ...
2 ! 3 ! 4 ! 5 ! 6 ! 7 ! 8 !
N términos
import java.io.*;
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lee numeros
i=0;
s=0;
}while(n!=i);
}//fin de main
}//fin de la clase
import java.io.*;
class perfecto
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
} while (d<num);
if (s==num)
System.out.println("El numero es
perfecto");
else
System.out.println("El numero no es
perfecto");
}
}
import java.io.*;
class nperfectos
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
} while (d<num);
if (s==num)
{ c++;
System.out.println(num);
}
} while(c<n);
}
}
sentencia 1;
sentencia 1;
sentencia 1;
...
sentencia 1;
o bien:
sentencia;
Donde:
2. Se evalúa la condición:
int i;
for (i = 1; i <= 100; i++)
System.out.print(i + “ “);
char car;
for (car=‘z’ ; car >= ‘a’; car--)
System.out.print(car + “ “);
for (;;)
x++;
import java.io.*;
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
for(;num10!=0;)
{ r=num10%4;
numn=numn+r*(int) Math.pow(10,i);
num10=num10/4;
i++;
}
import java.io.*;
class factorial
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
System.out.println(" = "+fact);
}
}
import java.io.*;
class nfactorial
{
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
int fact,n,num;
int i; //contador
System.out.print("Introduzca un numero : ");
sdato = flujoE.readLine(); // leer una línea de texto
num=Integer.parseInt(sdato);//convierte cadena
for(n=1;n<=num;n++)
{
System.out.println(" = "+fact);
}
}
continue;
MCD (60,36)=12
Residuo (r) 24 12 0
Cociente (q) 1 1 2
MCD (70,12)=2
Residuo (r) 10 2 0
Cociente (q) 5 1 5
import java.io.*;
class mcd
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
for( ; ; )
{
r=n1%n2;
n1=n2;
n2=r;
}
}
}
...
busqueda:
for (; i < maximo; i++) {
for (; j < maximo; j++) {
...
...
break busqueda;
}
}
Declarar el array
Crear el array
Usar el array
tipo_de_dato[] nombre_del_array;
tipo_de_dato nombre_del_array[];
PROGRAMACION CON JAVA 2 109
Para declarar un array de enteros escribimos
int[] numeros;
o int numeros[];
nombre=new tipo[tamaño];
numeros=new int[4];
por ejemplo:
numeros[0]=2;
numeros[1]=-4;
numeros[2]=15;
numeros[3]=-25;
{ numeros[i]=i*i+4; }
110 Ing. Gilmer Matos Vila
No necesitamos recordar el número de elementos del
array, este tiene un dato miembro llamado length que
nos proporciona la dimensión del array. Escribimos de
forma equivalente
{ numeros[i]=i*i+4;
{ System.out.println(nombres[i]);
}//fin de class
}
}
char[] cad={'F','I','S','-','U','N','C','P'};
int i;//contador
System.out.println("");
System.out.println("");
}//fin de class
2.4.1. CONSTRUCTORES
Se pueden crear instancias de String con el
operador new.
// s es la cadena "abc"
String s = "abad";
String s = "abc";
System.out.println(s.length());//imprimiría 3
String s = "abc";
System.out.println("abc".lenght());
Concatenación de cadenas
.append (edad)
.toString();
PROGRAMACION CON JAVA 2 119
que es lo que sucede cuando se ejecuta este
código. append añade cosas al final de
StringBuffer, y toString convierte a cadenas
el StringBuffer. Trataremos con detalle
append y toString mas adelante en este
capítulo.
Conversión de cadenas
class toStringDemo
{
public static void main(String args[]) {
Point p = new Point(10, 20);
System.out.println("p = " + p);
}
}
Esta versión de la clase Point incluye una
versión con la que se sobrescribe el método
toString del objeto, y que da formato a la
cadena que contiene los valores de x y de y
de cada instancia de Point. La salida de este
programa es la siguiente:
p = Punto[10, 20 ]
2.4.4. COMPARACIÓN
Si se desean comparar dos cadenas para ver si
son iguales, puede utilizar el método equals
de String. Devolverá true si el único
parámetro está compuesto de los mismos
caracteres que el objeto con el que se llama
a equals. Una forma alternativa de equals
llamada equalsIgnoreCase ignora si los
caracteres de las cadenas que se comparan
están en mayúsculas o minúsculas.
// si importa la diferencia
// no importa la diferencia
Ordenación
class SortString
{
static String arr[] = { "Ahora", "es", "el ",
"momento", "de", "actuar"};
public static void main(String args[])
{
System.out.println("La cadena inicial es");
for (int j = 0; j < arr.length; j++)
System.out.print(arr[j]+" ");
System.out.println("\n");
StringBuffer
append
124 Ing. Gilmer Matos Vila
Al método append de StringBuffer se le llama
a menudo a través del operador +. Tiene
versiones sobrecargadas para todos los tipos.
Se llama a String.valueOf para cada parámetro
y el resultado se aóade al StringBuffer
actual. Cada versión de append devuelve el
propio buffer.
es equivalente a:
System.out.println("abc");
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
Constructores
String()
String(StringBuffer buffer)
Allocates a new string that contains the sequence
of characters currently contained in the string buffer
argument.
//...sentencias
[return[(]expresión[)]];
return [(expresión)];
return ;
// Archivo Hipotenusa.java
import java.io.*;
class Hipotenusa
{
public static void main (String[] args)
throws IOException
{
PROGRAMACION CON JAVA 2 135
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura de datos
System.out.print("Introduzca primer cateto: ");
sdato = flujoE.readLine(); // leer una línea de texto
ca=Float.parseFloat(sdato);//convierte cadena a float
System.out.print("Introduzca segundo cateto: ");
sdato = flujoE.readLine(); // leer una línea de texto
cb=Float.parseFloat(sdato);//convierte cadena a float
import java.io.*;
class Hipotenusa1
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura de datos
System.out.print("Introduzca primer cateto: ");
sdato = flujoE.readLine(); // leer una línea de texto
ca=Float.parseFloat(sdato);//convierte cadena a float
System.out.print("Introduzca segundo cateto: ");
sdato = flujoE.readLine(); // leer una línea de texto
cb=Float.parseFloat(sdato);//convierte cadena a float
//llamado al método hipotenusa
hipotenusa(ca,cb);
// Archivo vectores.java
import java.io.*;
class vectores
{
public static void main (String[] args)
throws IOException
{
int [] v1= new int [4];//primer vector
int [] v2= new int [4];//segundo vector
int [] vs= new int [4];//vector que almacena el resultado
leer_vector(v1);
escribir_vector(v1);
leer_vector(v2);
escribir_vector(v2);
vs=and(v1,v2);
System.out.println("Contenido del vector AND:");
escribir_vector(vs);
}
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
}//fin de leer_vector
4.1. ATRIBUTOS
Los atributos son las características individuales que
diferencian un objeto de otro y determinan su
apariencia, estado u otras cualidades. Los atributos
se guardan en variables denominadas de instancia, y
cada objeto particular puede tener valores distintos
para estas variables.
4.2. COMPORTAMIENTO
El comportamiento de los objetos de una clase se
implementa mediante funciones miembro o métodos. Un
método es un conjunto de instrucciones que realizan
142 Ing. Gilmer Matos Vila
una determinada tarea y son similares a las funciones
de los lenguajes estructurados.
class NombreClase{
//funciones miembro
//...sentencias
[return[(]expresión[)]];
void funcion(....)
{
//sentencias...
}
double funcion(....)
{
double suma=0.0;
//sentencias...
return suma;
}
class Rectangulo{
int x;
int y;
int ancho;
int alto;
int calcularArea(){
return (ancho*alto);
}
}
class Rectangulo{
int x;
int y;
int ancho;
int alto;
void desplazar(int dx, int dy){
x+=dx;
y+=dy;
}
}
class Rectangulo{
int x;
int y;
int ancho;
int alto;
Rectangulo(int x1, int y1, int w, int h){
x=x1;
y=y1;
ancho=w;
alto=h;
}
}
class Rectangulo{
int x;
int y;
int ancho;
int alto;
Rectangulo(int w, int h){
x=0;
y=0;
ancho=w;
alto=h;
}
}
class Rectangulo{
int x;
int y;
int ancho;
int alto;
Rectangulo(){
x=0;
y=0;
ancho=0;
alto=0;
}
}
public Rectangulo()
{
x=0;
y=0;
ancho=0;
alto=0;
}
Por ejemplo,
objeto.miembro;
rect1.ancho=100;
rect1.calcularArea();
int medidaArea=rect1.calcularArea();
rect2.desplazar(10, 20);
rect2.desplazar(10, 20);
if(rect1.estaDentro(20,30))
{
System.out.println("El punto está dentro del
rectángulo");
}
else
{
System.out.println("El punto está fuera del
rectángulo");
}
}//fin main
}
Veamos un ejemplo
Si escribimos
rect3=rect1;
int calcularArea()
{
return (ancho*alto);
}
__________________________________
//archivo: RectanguloApp1.java
rect2.desplazar(10, 20);
if(rect1.estaDentro(20,30))
{
System.out.println("El punto (20,30) esta dentro
del rectangulo 1");
}
else
{
System.out.println("El punto (20,30) esta fuera
del rectangulo 1");
}
}//fin main
}
4.6. IDENTIFICADORES
Cómo se escriben los nombres de las variables, de las
clases, de las funciones, etc., es un asunto muy
importante de cara a la comprensión y el mantenimiento
de código. En la introducción a los fundamentos del
lenguaje Java hemos tratado ya de los identificadores.
objeto_de_la_clase.miembro_público_no_estático
clase.miembro_público_estático
//archivo: Linea.java
import java.io.*;
class Linea
{
//coordenada 1er punto, modificador de acceso:package
int x1,y1;
//coordenada 2do punto, modificador de acceso:package
int x2,y2;
//lectura
System.out.println("Introduzca 1er punto: ");
System.out.print("x1: ");
sdato = flujoE.readLine(); // leer una línea de texto
x1=Integer.parseInt(sdato);//convierte cadena
System.out.print("y1: ");
sdato = flujoE.readLine(); // leer una línea de texto
y1=Integer.parseInt(sdato);//convierte cadena
// Archivo LineaAppl.java
import java.io.*;
class LineaAppl
{
public static void main (String[] args)
{
//Creación de un objeto recta: r1
Linea r1=new Linea();
// uso del objeto r1
r1.leer();
r1.escribir();
}
}
//archivo: Linea1.java
import java.io.*;
class Linea1
{
//coordenada 1er punto, modificador de acceso:package
int x1,y1;
//coordenada 2do punto, modificador de acceso:package
int x2,y2;
//lectura
System.out.println("Introduzca 1er punto: ");
System.out.print("x1: ");
sdato = flujoE.readLine(); // leer una línea de texto
x1=Integer.parseInt(sdato);//convierte cadena
System.out.print("y1: ");
sdato = flujoE.readLine(); // leer una línea de texto
y1=Integer.parseInt(sdato);//convierte cadena
// Archivo Linea1Appl.java
import java.io.*;
class Linea1Appl
{
public static void main (String[] args)
{
//Creación de un objeto recta: r1
Linea1 r1=new Linea1();
// uso del objeto r1
r1.leer();
r1.escribir();
}
}
//archivo: Linea2.java
import java.io.*;
class Linea2
{
//coordenada 1er punto, modificador de acceso:privado
private int x1,y1;
//coordenada 2do punto, modificador de acceso:privado
private int x2,y2;
//los datos miembro solo seran accedidos por su métodos
//por ser privados
//lectura
System.out.println("Introduzca 1er punto: ");
System.out.print("x1: ");
sdato = flujoE.readLine(); // leer una línea de texto
x1=Integer.parseInt(sdato);//convierte cadena
System.out.print("y1: ");
sdato = flujoE.readLine(); // leer una línea de texto
y1=Integer.parseInt(sdato);//convierte cadena
}
164 Ing. Gilmer Matos Vila
// Archivo Linea2Appl.java
import java.io.*;
class Linea2Appl
{
public static void main (String[] args)
{
//Creación de un objeto recta: r1
Linea2 r1=new Linea2();
// uso del objeto r1
r1.leer();
r1.escribir();
}
}
//archivo: Linea3.java
import java.io.*;
class Linea3
{
//coordenada 1er punto, modificador de acceso:público
public int x1,y1;
//coordenada 2do punto, modificador de acceso:público
PROGRAMACION CON JAVA 2 165
public int x2,y2;
//los datos miembro solo seran accedidos por su métodos
//por ser privados
//lectura
System.out.println("Introduzca 1er punto: ");
System.out.print("x1: ");
sdato = flujoE.readLine(); // leer una línea de texto
x1=Integer.parseInt(sdato);//convierte cadena
System.out.print("y1: ");
sdato = flujoE.readLine(); // leer una línea de texto
y1=Integer.parseInt(sdato);//convierte cadena
}
// Archivo Linea3Appl.java
import java.io.*;
class Linea3Appl
{
public static void main (String[] args)
{
//Creación de un objeto recta: r1
Linea3 r1=new Linea3();
// uso del objeto r1
r1.x1=10;r1.y1=11;
r1.x2=100;r1.y2=101;
System.out.println("x1="+r1.x1+" y1="+r1.y1);
System.out.println("x2="+r1.x2+" y2="+r1.y2);
//como el modificador de acceso de los métodos
//de la clase Linea es public
//entonces main() puede accesar a
//leer() y escribir(), para modificar sus datos
//miembro
System.out.println("Valores para modificar la recta:");
r1.leer();
r1.escribir();
}
}
//archivo tiempo.java
import java.io.*;
class tiempo
{ //hora minutos y segundos
private int hora,min,seg;
return dif;
}
}
//archivo: exa2p120032App.java
import java.io.*;
class exa2p120032App
{
public static void main (String[] args)
throws IOException
{ tiempo t1=new tiempo();tiempo t2=new tiempo();
tiempo trans=new tiempo();
System.out.println("Ingrese tiempo :");
t1.leer_tiempo(); t1.escribir_tiempo();
class Complejo
{ private float real;
private float imaginario;
Complejo()
{ real=0;
imaginario=0;
}
_________________________________________
// Archivo ComplejoAppl.java
import java.io.*;
class ComplejoAppl
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura de datos
System.out.print("Introduzca parte real: ");
sdato = flujoE.readLine(); // leer una línea de texto
re=Float.parseFloat(sdato);//convierte cadena a float
System.out.print("Introduzca parte imaginaria: ");
sdato = flujoE.readLine(); // leer una línea de texto
im=Float.parseFloat(sdato);//convierte cadena a float
}
}
//archivo: quebrado.java
import java.io.*;
class quebrado
{
private int n;//numerador
private int d;//denominador
//lectura
PROGRAMACION CON JAVA 2 171
System.out.print("Introduzca numerador: ");
sdato = flujoE.readLine(); // leer una línea de texto
n=Integer.parseInt(sdato);//convierte cadena
System.out.print("Introduzca denominador: ");
sdato = flujoE.readLine(); // leer una línea de texto
d=Integer.parseInt(sdato);//convierte cadena
}
catch (IOException ignorada)
{}
}
//archivo: quebradoAppl.java
}//fin main
}
// Archivo: Cuenta.java
import java.lang.Math;
class Cuenta
{ private float saldo;
import java.io.*;
class CuentaAppl
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura de datos
System.out.print("Introduzca saldo inicial: ");
sdato = flujoE.readLine(); // leer una línea de texto
sal=Float.parseFloat(sdato);//convierte cadena a float
c.asignar(sal);
c.escribir();
c.deposito(dep);
c.escribir();
c.retiro(ret);
c.escribir();
}
}
// Archivo: Cuenta1.java
import java.io.*;
class Cuenta1
{ private float saldo;
// Archivo Cuenta1Appl.java
import java.io.*;
class Cuenta1Appl
{
public static void main (String[] args)
throws IOException
{
//Creación de un objeto Cuenta1
Cuenta1 c=new Cuenta1();
c.asignar();
c.escribir();
c.deposito();
c.escribir();
c.retiro();
c.escribir();
}
}
// Archivo: Cuenta2.java
import java.io.*;
class Cuenta2
{ private float saldo;
// Archivo Cuenta2Appl.java
import java.io.*;
class Cuenta2Appl
{
public static void main (String[] args)
{
//Creación de un objeto Cuenta2: c
Cuenta2 c=new Cuenta2();
c.asignar();
c.escribir();
c.deposito();
c.escribir();
c.retiro();
c.escribir();
}
}
//archivo: Conjunto.java
import java.io.*;
import java.lang.String.*;
class Conjunto
{
private char [] e;//elemento del conjunto
System.out.println("}");
}
return u;
}
//archivo: ConjuntoAppl.java
c1.leer();
c1.escribir();
c2.leer();
c2.escribir();
System.out.println("Conjunto union");
c=c1.union(c2);
c.escribir();
}//fin main
}
//archivo: Conjunto1.java
import java.io.*;
import java.lang.String.*;
class Conjunto1
{
private char [] e;//elemento del conjunto
//lectura
System.out.print("Elementos del conjunto como cadena: ");
System.out.println("}");
}
return u;
}
//archivo: Conjunto1Appl.java
c1.leer();
c1.escribir();
c2.leer();
c2.escribir();
System.out.println("Conjunto union");
c=c.union(c1,c2);
c.escribir();
}//fin main
}
//archivo enterazo.java
import java.io.*;
class enterazo
{ //arreglo que almacena los dígitos de un número
//consideremos tres cifras
private int[] valor;
int aux,acarreo=0;
acarreo=0;
// Recorre las cifras del segundo número y
// lo almacena en 2do término suma n2[]
in=tam-2;//derecha del 2do término de la suma
j=ent2.valor.length-2;// cifra 2do enterazo
for(i=valor.length-1;i>=0;i--)
{ aux=valor[i]*ent2.valor[j]+acarreo;
n2[in]=aux%10;
acarreo=aux/10;
in--;
}
n2[in]=acarreo;
acarreo=0;
// Recorre las cifras del segundo número y
// lo almacena en 3er término suma n3[]
in=tam-3;//derecha del 3er término de la suma
j=ent2.valor.length-3;// cifra derecha 2do enterazo
acarreo=0;
//suma de los tres términos
for(i=n1.length-1;i>=0;i--)
{ aux=n1[i]+n2[i]+n3[i]+acarreo;
mult.valor[i]=aux%10;
acarreo=aux/10;
}
return mult;
}
}
//archivo: exa2p220032App.java
import java.io.*;
class exa2p220032App
{
public static void main (String[] args)
throws IOException
{ enterazo e1=new enterazo();enterazo e2=new enterazo();
enterazo em=new enterazo();
e1.asignar();
System.out.println("primer numero: ");e1.mostrar();
e2.asignar();
System.out.println("segundo numero: ");e2.mostrar();
em=e1.multiplicar(e2);
System.out.println("multiplicacion: ");em.mostrar();
}
}
//archivo: quebrado1.java
import java.io.*;
class quebrado1
{
private int n;//numerador
private int d;//denominador
//lectura
System.out.print("Introduzca numerador: ");
sdato = flujoE.readLine(); // leer una línea de texto
n=Integer.parseInt(sdato);//convierte cadena
System.out.print("Introduzca denominador: ");
sdato = flujoE.readLine(); // leer una línea de texto
d=Integer.parseInt(sdato);//convierte cadena
}
catch (IOException ignorada)
{}
}
}//fin main
}
// Atributos
private double x, y; // coordenadas del centro
private double r; // el radio
double area()
{
return 3.14159*r*r;
}
…
a = c.area();
a = c.area();
// Métodos
public double circunferencia() {
return 2*3.14159*r;
}
public Circulo () {
x = 0.0;
y = 0.0;
r = 1.0;
}
//Métodos
public double circunferencia() {
return 2*3.14159*r;
}
//archivo Circulo.java
class Circulo
{
// Atributos
private double x, y, r;
public Circulo ()
{
x = 0.0;
y = 0.0;
r = 1.0;
}
//Métodos
public double circunferencia()
{
return 2*3.14159*r;
}
import java.io.*;
class CirculoApp
{
public static void main (String[] args)
{
Circulo c1=new Circulo();
System.out.print("Circunferencia del circulo 1: ");
System.out.println(c1.circunferencia());
System.out.print("Area del circulo 1: ");
System.out.println(c1.area());
public Circulo1 ()
{
this (0.0, 0.0, 1.0); //Estamos llamando a (1)
}
//Métodos
public double circunferencia()
{
return 2*3.14159*r;
}
//Archivo Circulo1.java
class Circulo1
{
// Atributos
private double x, y, r;
public Circulo1 ()
{
this (0.0, 0.0, 1.0);//Estamos llamando a (1)
}
//Métodos
public double circunferencia()
{
return 2*3.14159*r;
}
import java.io.*;
class Circulo1App
{
public static void main (String[] args)
{
Circulo c1=new Circulo();
System.out.print("Circunferencia del circulo 1: ");
System.out.println(c1.circunferencia());
System.out.print("Area del circulo 1: ");
System.out.println(c1.area());
class Persona
{
private String nombre;
private float sueldo;
p[i].leer();
p[i].escribir();
//Archivo: Personaa.java
import java.io.*;
class Personaa
{
private String nombre;
private float sueldo;
//lectura
System.out.print("nombre: ");
nombre= flujoE.readLine(); // leer una línea de texto
System.out.print("sueldo: ");
sdato = flujoE.readLine(); // leer una línea de texto
sueldo=Float.parseFloat(sdato);//convierte cadena
}
catch (IOException ignorada)
{}
}
import java.io.*;
class PersonaApp
{
public static void main (String[] args)
throws IOException
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//otras variables
int i;//contador
float prom;//promedio de los sueldos
float sueldos=0;//acumulador de los sueldos
//inicializaciòn de objetos
for (i=0;i<p.length;i++)
p[i]=new Persona();
//lectura de datos
System.out.println("Ingrese datos de las personas: ");
for (i=0;i<p.length;i++)
p[i].leer();
//Impresión de datos
System.out.println("Datos de las personas: ");
for (i=0;i<p.length;i++)
{
System.out.println("Persona No. "+i);
p[i].escribir();
sueldos+=p[i].obtener_sueldo();
}
// Constructores
public Circulo2 (double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
numCirculos++;
}
public Circulo2 ()
{
this (0.0, 0.0, 1.0);
}
//Métodos
public double circunferencia()
{
return 2*3.14159*r;
}
//Archivo Circulo2.java
// Constructores
public Circulo2 (double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
numCirculos++;
}
public Circulo2 ()
{
this (0.0, 0.0, 1.0);
}
//Métodos
public double circunferencia()
{
return 2*3.14159*r;
}
import java.io.*;
class Circulo2App
{
public static void main (String[] args)
throws IOException
{
Circulo2 c1=new Circulo2();
System.out.print("Circunferencia del circulo 1: ");
System.out.println(c1.circunferencia());
System.out.print("Area del circulo 1: ");
System.out.println(c1.area());
}
}
Circulo.PI = 4;
//archivo: Libro.java
import java.io.*;
class Libro
{
//variables de clase
static int cantidad;
static float total=0;
//datos miembro
private String titulo;
private float precio;
//funciones miembro
public void leer_datos()
{
try
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new
InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
//lectura
System.out.print("Introduzca titulo: ");
PROGRAMACION CON JAVA 2 207
titulo = flujoE.readLine(); // leer una línea de texto
System.out.print("Introduzca precio: ");
sdato = flujoE.readLine(); // leer una línea de texto
precio=Float.parseFloat(sdato);//convierte cadena
}
catch (IOException ignorada)
{}
total=total+precio*cantidad;
}//fin leer
// Archivo LibroAppl.java
class LibroAppl
{
public static void main (String[] args)
{
//Creación de los objetos libro: li1,li2,li3
Libro li1=new Libro();
Libro li2=new Libro();
Libro li3=new Libro();
System.out.println("Ingrese datos del primer libro");
li1.leer_datos();
System.out.println("Ingrese datos del segundo libro");
li2.leer_datos();
System.out.println("Ingrese datos del tercer libro");
li3.leer_datos();
//escribe el total
//puede utilizar cualquiera de los objetos
li1.escribir_total_compra();
}
}
Características:
//....
//MÉTODO DE INSTANCIA. DEVUELVE EL MAYOR DE LOS DOS CÍRCULOS
public Circulo3 elMayor (Circulo3 c)
{
if (c.r > r)
return c;
else
return this;
}
//....
}
//archivo: Circulo3.java
// Constructores
Circulo3 (double x, double y, double r)
{ this.x = x; this.y = y; this.r = r;
}
//Métodos:
// Archivo Circulo3App.java
import java.io.*;
class Circulo3App
{
public static void main (String[] args)
throws IOException
{
Solución:
Primera columna:
Tercera columna
Cuarta columna
k=0
k=1
k=2
Archivo Matriz.java
class Matriz
{
Archivo MatrizAppl.java
class MatrizAppl
{
if ( c != null )
System.out.println("El Circulo 'c' existe !");
218 Ing. Gilmer Matos Vila
Circulo b=null; // b referencia a null
if ( b == null )
System.out.println("El Circulo 'b' NO existe !");
Automóviles
ventana.mostrar();
ventana.cambiarDimensiones(10, 10);
ventana.mostrar();
super(x, y, w, h);
super.mostrar();
ventana.mostrar();
ventana.desplazar(4, 3);
ventana.cambiarDimensiones(10, -5);
//Archivo: Ventana.java
class Ventana
{
protected int x;
protected int y;
protected int ancho;
protected int alto;
//Archivo: VentanaTitulo.java
//Archivo: VentanaApp.java
class VentanaApp
{
//Archivo: Figura.java
//Archivo: FiguraApp.java
236 Ing. Gilmer Matos Vila
class FiguraApp
{
public static void main(String[] args)
{
//enlace temprano
Circulo c=new Circulo(0, 0, 5.5);
System.out.println("Utilizacion de enlace temprano");
System.out.println("Area del circulo "+c.area());
Rectangulo r=new Rectangulo(0, 0, 5.5, 2.0);
System.out.println("Area del rectangulo "+r.area());
//enlace tardío
System.out.println("Utilizacion de enlace tardio
(dinamico)");
Figura f=new Circulo(0, 0, 5.5);
System.out.println("Area del circulo "+f.area());
f=new Rectangulo(0, 0, 5.5, 2.0);
System.out.println("Area del rectangulo "+f.area());
}
}
GESTION DE EXCEPCIONES
int numero=Integer.parseInt(str);
Objeto no inicializado
String str;
str.length();
//...
Entrada/salida
PROGRAMACION CON JAVA 2 241
En otras situaciones el mensaje de error
aparece en el momento en el que se compila el
programa. Así, cuando intentamos leer un
carácter del teclado, llamamos a la la
función
System.in.read();
try
{
System.in.read();
}
catch (IOException ex)
{ }
java.lang.NumberFormatException: 12
Try
{
//...
}
catch(NumberFormatException ex)
{
System.out.println(ex.getMessage());
}
class ExcepcionApp
{
public static void main(String[] args)
{
String str1="12";
String str2="0";
String respuesta;
int numerador, denominador, cociente;
try
{
numerador=Integer.parseInt(str1);
denominador=Integer.parseInt(str2);
cociente=numerador/denominador;
respuesta=String.valueOf(cociente);
}
catch(NumberFormatException ex)
{
respuesta="Se han introducido caracteres no
numericos";
}
catch(ArithmeticException ex)
{
respuesta="Division entre cero";
}
System.out.println(respuesta);
}
}
try
{
//Este código puede generar una excepción
}catch(Exception ex)
{
//Este código se ejecuta cuando se produce una excepción
}finally
{
//Este código se ejecuta cuando se produzca o no una
excepción
}
respuesta=String.valueOf(cociente);
PAQUETES
6.1. PAQUETES
Un paquete es un conjunto de clases, lógicamente
relacionadas entre sí, agrupadas bajo un nombre (por
ejemplo, el paquete java.io agrupa las clases que
permiten a un programa realizar la entrada y salida de
información); incluso, un paquete puede contener a
otros paquetes.
package java.awt.imagen;
3
La ejecución de la clase Paquete.Prueba se realiza desde la línea de comandos del DOS.
PROGRAMACION CON JAVA 2 255
Para realizar modificaciones de CLASSPATH en
el JCreator, que nos permita definir la
ubicación de nuestros paquetes, debemos
hacerlo utilizando Configure, Options, JDK
Profiles, Edit, Add; tal como se muestra en
la figura 5.1.
Figura PAQUETES.6.
import java.util.Date;
import java.io.*;
private Sí No No No
protected Sí Sí Sí No
public Sí Sí Sí Sí
package Sí No Sí No
Paquete Descripción
Contiene las clases necesarias para crear
java.applet applets que se ejecutan en la ventana del
navegador
Contiene clases para crear una aplicación
java.awt
GUI independiente de la plataforma
Entrada/Salida. Clases que definen
java.io
distintos flujos de datos
Contiene clases esenciales, se importa
java.lang impícitamente sin necesidad de una
sentencia import.
Se usa en combinación con las clases del
java.net paquete java.io para leer y escribir
datos en la red.
Contiene otras clases útiles que ayudan
java.util
al programador
//Archivo Leer.java
// Debe estar en la carpeta LeerDatos dentro del
// directorio activo
package LeerDatos;
import java.io.*;
public class Leer
{
public static String dato()
{
String sdato = "";
try
{
// Definir un flujo de caracteres de entrada: flujoE
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader flujoE = new BufferedReader(isr);
PROGRAMACION CON JAVA 2 259
// Leer. La entrada finaliza al pulsar la tecla Entrar
sdato = flujoE.readLine();
}
catch(IOException e)
{
System.err.println("Error: " + e.getMessage());
}
return sdato; // devolver el dato tecleado
}
//Archivo: LecturaDatos.java
class LecturaDatos
{
public static void main(String[] args)
{
short dato_short = 0;
int dato_int = 0;
long dato_long = 0;
float dato_float = 0;
double dato_double = 0;
System.out.println(dato_short);
System.out.println(dato_int);
System.out.println(dato_long);
System.out.println(dato_float);
System.out.println(dato_double);
}
}
INTERFACES
//Archivo Animal.java
package polimorfismo;
package polimorfismo;
7.3.2. INTERFACES
Vamos a crear un interface denominado
Parlanchin que contenga la declaración de una
función denominada habla.
//Archivo: Parlanchin.java
public interface Parlanchin
{
public abstract void habla();
}
//Archivo Animal1.java
//archivo: Reloj.java
//Archivo: PoliApp1.java
File(String path)
String getName()
String getPath()
String getAbsolutePath()
boolean exists()
boolean canWrite()
boolean canRead
boolean isFile()
boolean isDirectory()
boolean isAbsolute()
long lastModified()
long length()
boolean mkdir()
boolean mkdirs()
boolean delete()
String[] list()
if(fichero.exists())
{
System.out.println("Nombre del archivo
"+fichero.getName());
System.out.println("Camino
"+fichero.getPath());
System.out.println("Camino absoluto
"+fichero.getAbsolutePath());
System.out.println("Se puede escribir
"+fichero.canRead());
System.out.println("Se puede leer
"+fichero.canWrite());
System.out.println("Tamaño "+fichero.length());
}
fichero=new File(".");
La salida es la siguiente
archivo1.jpr
archivo1.html
ArchivoApp1.java
ArchivoApp1.~jav
Filtro.java
Filtro.~jav
import java.io.*;
public class Filtro implements FilenameFilter
{
String extension;
Filtro(String extension)
{
this.extension=extension;
276 Ing. Gilmer Matos Vila
}
public boolean accept(File dir, String name)
{
return name.endsWith(extension);
}
}
listaArchivos=fichero.list(new Filtro(".java"));
for(int i=0; i<listaArchivos.length; i++)
{
System.out.println(listaArchivos[i]);
}
ArchivoApp1.java
Filtro.java
//Archivo: Filtro.java
import java.io.*;
Filtro(String extension)
{
this.extension=extension;
}
//Archivo: ArchivoApp1.java
import java.io.*;
}
}
}
import java.io.*;
byte, 8 bits.
8.2.2. LECTURA
Las clases Reader e InputStream son similares
aunque se refieren a distintos tipos de
datos, lo mismo ocurre con Writer y
OutputSream.
int read()
int read()
int write(int c)
int write(int c)
try
{
System.in.read();
}catch (IOException ex) { }
System.out.println(str);
System.out.println(str);
//Archivo TecladoApp2.java
import java.io.*;
try
{
//espera la pulsación de una tecla y luego RETORNO
System.in.read();
}catch (Exception e) { }
}
}
PROGRAMACION CON JAVA 2 285
Podemos usar la segunda versión de la función
read para leer el conjunto de caracteres
tecleados por el usuario. (Vea el archivo
TecladoApp1.java)
char[] buffer=new char[255];
try
{
Reader entrada=new InputStreamReader(System.in);
int numBytes=entrada.read(buffer);
System.out.println("Número de bytes leídos "+numBytes);
}catch(IOException ex){ }
System.out.println(str);
import java.io.*;
try
{
//espera la pulsación de una tecla y luego RETORNO
System.in.read();
}catch (Exception e)
{ }
}
}
System.out.println(str);
// Archivo: ArchivoApp2.java
import java.io.*;
try
288 Ing. Gilmer Matos Vila
{
entrada=new FileReader("mensaje.txt");
int c;
while((c=entrada.read())!=-1)
{
str.append((char)c);
}
System.out.println(str);
System.out.println("-------------------------------
-------");
}catch (IOException ex)
{
System.out.println(ex);
}
finally
{
//cerrar los flujos de datos
if(entrada!=null)
{
try
{
entrada.close();
}catch(IOException ex){}
}
System.out.println("el bloque finally siempre se
ejecuta");
}
}
}
8.4.2. LECTURA/ESCRITURA
Los pasos para leer y escribir en disco son
los siguientes:
entrada=new FileReader("mensaje.txt");
salida=new FileWriter("copia.txt");
entrada.close();
salida.close();
import java.io.*;
try
{
entrada=new FileReader("mensaje.txt");
salida=new FileWriter("copia.txt");
//entrada=new FileInputStream("mensaje.txt");
//salida=new FileOutputStream("copia.txt");
int c;
while((c=entrada.read())!=-1)
{
salida.write(c);
}
}
catch (IOException ex)
{
System.out.println(ex);
}
finally
{
//cerrar los flujos de datos
if(entrada!=null)
{
try
{
entrada.close();
290 Ing. Gilmer Matos Vila
}catch(IOException ex){}
}
if(salida!=null)
{
try
{
salida.close();
}catch(IOException ex){}
}
System.out.println("el bloque finally siempre se
ejecuta");
}
}
}
boolean readBoolean();
byte readByte();
int readUnsignedByte();
short readShort();
int readUnsignedShort();
char readChar();
int readInt();
String readLine();
long readLong();
float readFloat();
double readDouble();
Escritura Lectura
Un carácter writeChar readChar
Un entero writeInt readInt
Un número
writeDouble readDouble
decimal
Un string writeChars readLine
PROGRAMACION CON JAVA 2 293
Veamos el código que escribe los datos a un
archivo pedido.txt en disco
try
{
while(true)
{
descripcion=entrada.readLine();
unidad=entrada.readInt();
entrada.readChar(); //lee el carácter tabulador
precio=entrada.readDouble();
System.out.println("has pedido "+unidad+"
"+descripcion+" a "+precio+" soles.");
total=total+unidad*precio;
}
}catch (EOFException e)
{
System.out.println("Excepción cuando se alcanza el final
del archivo");
}
try
{
while ((descripcion=entrada.readLine())!=null)
{
unidad=entrada.readInt();
entrada.readChar();//lee el carácter tabulador
precio=entrada.readDouble();
System.out.println("has pedido "+unidad+"
"+descripcion+" a "+precio+" soles.");
total=total+unidad*precio;
}
System.out.println("Final del archivo");
}catch (EOFException e)
296 Ing. Gilmer Matos Vila
{
System.out.println("Excepción cuando se alcanza el final
del archivo");
}
//Archivo: ArchivoApp7.java
import java.io.*;
while ((descripcion=entrada.readLine())!=null)
{
//descripcion=entrada.readLine();
unidad=entrada.readInt();
entrada.readChar();//lee el carácter tabulador
precio=entrada.readDouble();
System.out.println("has pedido "+unidad+"
"+descripcion+" a "+precio+" Soles.");
PROGRAMACION CON JAVA 2 297
total=total+unidad*precio;
}
System.out.println("Final del archivo");
}
catch (EOFException e)
{
System.out.println("Excepción cuando se alcanza el
final del archivo");
}
System.out.println("por un TOTAL de: "+total+" soles.");
entrada.close();
}
}
La persistencia
import java.io.*;
public interface Serializable
{
}
Para hacer una clase serializable simplemente
ha de implementar el interface Serializable,
por ejemplo, si se tiene la clase Lista, se
añade la implementación del interface
8.6.2. LECTURA/ESCRITURA
Dos flujos de datos ObjectInputStream y
ObjectOutputStream están especializados en la
lectura y escritura de objetos. El
comportamiento de estos dos flujos es similar
a sus correspondientes que procesan flujos de
datos primitivos DataInputStream y
DataOutputStream.
salida.close();
entrada.close();
public Lista(int[] x)
{
this.x=x;
n=x.length;
ordenar();
}
// Archivo: ArchivoApp4.java
import java.io.*;
import java.util.*;
}
}
// Archivo: Cliente.java
// Archivo: ArchivoApp6.java
import java.io.*;
try
{
ObjectOutputStream salida=new
ObjectOutputStream(new FileOutputStream("cliente.obj"));
salida.writeObject("Datos del cliente\n");
salida.writeObject(cliente);
salida.close();
public Punto()
{
x=0;
y=0;
}
//Archivo: Rectangulo.java
public class Rectangulo implements java.io.Serializable
{
private int ancho ;
private int alto ;
private Punto origen;
public Rectangulo()
{
origen = new Punto(0, 0);
ancho=0;
alto=0;
}
public Rectangulo(Punto p)
{
this(p, 0, 0);
310 Ing. Gilmer Matos Vila
}
// Archivo: ArchivoApp5.java
import java.io.*;
try
{
ObjectOutputStream salida=new
ObjectOutputStream(new FileOutputStream("figura.obj"));
salida.writeObject("guardar un objeto
compuesto\n");
salida.writeObject(rect);
salida.close();
8.6.5. LA HERENCIA
En el apartado anterior hemos examinado la
composición, ahora examinemos la herencia. En
el capítulo de la herencia examinamos una
jerarquía formada por una clase base
denominada Figura y dos clases derivadas
denominadas Circulo y Rectangulo.
// Archivo: Figura.java
314 Ing. Gilmer Matos Vila
public abstract class Figura implements java.io.Serializable
{
protected int x;
protected int y;
try
{
ObjectOutputStream salida=new
ObjectOutputStream(new FileOutputStream("figura.obj"));
salida.writeObject("guardar un objeto de una clase
derivada\n");
salida.writeObject(fig1);
salida.writeObject(fig2);
salida.close();
APPLETS
import java.applet.*;
public class Applet1 extends Applet
{
}
import java.applet.*;
Métodos fundamentales
public class Simple extends Applet
{
. . .
public void init() { . . . }
public void start() { . . . }
public void stop() { . . . }
public void destroy() { . . . }
. . .
}
//Archivo: Applet1.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Líneas
Círculos y elipses
Rectángulos y polígones
Imágenes
Texto
El sistema de coordenadas
que se usa en Java es
similar a Windows. El área
X de trabajo del applet está
compuesta por una matriz
bidimensional de puntos o
pixels. Decimos que un
punto tiene coordenadas
Y (x, y) cuando está en la
columna x medida desde la
izquierda, y está en la
fila y, medida desde
arriba.
La esquina superior izquierda es el
origen (0, 0).
334 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
La esquina inferior derecha viene
determinada por las dimensiones del
componente. La función getSize nos
devuelve un objeto de la clase
Dimension cuyos miembros width y
height nos suministran la anchura y
altura del componente.
int ancho=getSize().width;
int alto=getSize().heigth;
g.setColor(Color.cyan);
g.setColor(Color.red);
g.fillRect(50, 150, 50, 60);
g.setColor(Color.cyan);
g.fillArc(10, 10, 150, 100, 0, 270);
g.setColor(Color.black);
g.drawArc(10, 10, 150, 100, 0, 270);
// Archivo: FuncionesApplet.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
g.setColor(Color.red);
g.fillRect(50, 150, 50, 60);
g.setColor(Color.cyan);
g.fillArc(10, 10, 150, 100, 0, 270);
g.setColor(Color.black);
g.drawArc(10, 10, 150, 100, 0, 270);
Green
Nombre Red (rojo) Blue (azul)
(verde)
white 255 255 255
lightGray 192 192 192
gray 128 128 128
drakGray 64 64 64
black 0 0 0
red 255 0 0
pink 255 175 175
orange 255 200 0
yellow 255 255 0
340 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
green 0 255 0
magenta 255 0 255
cyan 0 255 255
blue 0 0 255
g.setColor(Color.pink);
// Archivo: PaintRect.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
String[] nombreFuentes=getToolkit().getFontList();
for(int i=0; i<nombreFuentes.length; i++){
System.out.println(nombreFuentes[i]);
}
// Archivo: FontApplet2.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public FontApplet2()
{
}
//Initialize the applet
348 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
public void init()
{
try
{
jbInit();
}
catch (Exception e)
{
e.printStackTrace();
}
}
y+=3*hFont;
g.setColor(Color.black);
texto="leading ="+leading;
g.drawString(texto, 10, y);
texto="ascent ="+ascent;
y+=hFont;
g.drawString(texto, 10, y);
texto="descent ="+descent;
y+=hFont;
g.drawString(texto, 10, y);
texto="altura=ascent+descent+leading= "+
(ascent+descent+leading);
y+=hFont;
g.drawString(texto, 10, y);
}
}
// Archivo: GraficaParabola.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.Math;
}
public void paint(Graphics g)
{
double x,y; //(x, y) : coordenadas cartesianas
int x0,y0; //(x0, y0): origen de las coordenadas
cartesianas
// en la pantalla
int xp,yp; //(xp, yp) : coordenadas de pantalla
x0 = 200;
y0 = 200;
//dibuja ejes
g.drawLine(0,y0,400,y0);
g.drawLine(x0,0,x0,400);
//dibuja parabola
for(x=-300;x<=300;x++)
{
PROGRAMACION CON JAVA 2 351
y=x*x;
//convertir a coordenadas de pantalla
xp=(int)(x0+x);
yp=(int)(y0-y);
//dibujar punto
g.drawOval(xp,yp,2,2);
}
}
}
<HTML>
<HEAD>
<TITLE> Applet en Java </TITLE>
</HEAD>
<BODY>
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.lang.Math;
}
public void paint(Graphics g)
{
double x,y; //(x, y) : coordenadas cartesianas
int x0,y0; //(x0, y0): origen de las coordenadas
cartesianas
// en la pantalla
double xp,yp; //(xp, yp) : coordenadas de pantalla
double angrad;
x0 = 400;
y0 = 200;
//dibuja ejes
g.drawLine(0,y0,800,y0);
g.drawLine(x0,0,x0,400);
//dibuja parabola
for(x=-400;x<=400;x++)
{
angrad=Math.toRadians(x);
y=100*Math.sin(angrad);
//convertir a coordenadas de pantalla
xp=x0+x;
yp=y0-y;
//dibujar punto
g.drawOval((int) xp,(int) yp,2,2);
}
}
}
9.7.1. COMPONENTES
Hay dos tipos de componentes:
los controles
los paneles
java.lang.Object
|
+--java.awt.Component
|
+--java.awt.Label
Resumén de atributos
static int CENTER
Indicates that the label should be
centered.
static int LEFT
Indicates that the label should be left
justified.
static int RIGHT
Indicates that the label should be right
justified.
Resumén de Métodos
void addNotify()
Creates the peer for this label.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext
associated with this Label.
int getAlignment()
Gets the current alignment of this
label.
String getText()
Gets the text of this label.
protected String paramString()
Returns a string representing the
state of this Label.
void setAlignment(int alignment)
Sets the alignment for this label
to the specified alignment.
void setText(String text)
Sets the text for this label to the
specified text.
Resumén de atributos
static float BOTTOM_ALIGNMENT
358 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
Ease-of-use constant for getAlignmentY.
static float CENTER_ALIGNMENT
Ease-of-use constant for getAlignmentY and
getAlignmentX.
static float LEFT_ALIGNMENT
Ease-of-use constant for getAlignmentX.
static float RIGHT_ALIGNMENT
Ease-of-use constant for getAlignmentX.
static float TOP_ALIGNMENT
Ease-of-use constant for getAlignmentY().
Resumén de Constructores
protected Component()
Constructs a new component.
Resumen de Métodos
boolean action(Event evt, Object what)
Deprecated. As of JDK version 1.1, should
register this component as ActionListener on
component which fires action events.
void add(PopupMenu popup)
Adds the specified popup menu to the
component.
void addComponentListener(ComponentListener l)
Adds the specified component listener to
receive component events from this component.
void addFocusListener(FocusListener l)
Adds the specified focus listener to
receive focus events from this component when this
component gains input focus.
void addHierarchyBoundsListener(HierarchyBoundsListener l)
Adds the specified hierarchy bounds
listener to receive hierarchy bounds events from
this component when the hierarchy to which this
container belongs changes.
void addHierarchyListener(HierarchyListener l)
Adds the specified hierarchy listener to
receive hierarchy changed events from this component
when the hierarchy to which this container belongs
Hierarchy getHierarchyListeners()
Listener[] Returns an array of all the hierarchy
listeners registered on this component.
boolean getIgnoreRepaint()
InputCont getInputContext()
ext Gets the input context used by this
component for handling the communication with input
methods when text is entered in this component.
InputMeth getInputMethodListeners()
odListener Returns an array of all the input method
[] listeners registered on this component.
InputMeth getInputMethodRequests()
odRequests Gets the input method request handler
which supports requests from input methods for this
component.
KeyListen getKeyListeners()
er[] Returns an array of all the key listeners
registered on this component.
EventList getListeners(Class listenerType)
ener[] Returns an array of all the objects
currently registered as FooListeners upon this
Component.
Locale getLocale()
Gets the locale of this component.
Point getLocation()
Gets the location of this component in the
form of a point specifying the component's top-left
corner.
Point getLocation(Point rv)
Stores the x,y origin of this component
into "return value" rv and return rv.
Point getLocationOnScreen()
Gets the location of this component in the
form of a point specifying the component's top-left
corner in the screen's coordinate space.
Dimension getMaximumSize()
Gets the maximum size of this component.
Dimension getMinimumSize()
366 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
Gets the mininimum size of this component.
MouseList getMouseListeners()
ener[] Returns an array of all the mouse
listeners registered on this component.
MouseMoti getMouseMotionListeners()
onListener Returns an array of all the mouse motion
[] listeners registered on this component.
MouseWhee getMouseWheelListeners()
lListener[ Returns an array of all the mouse wheel
] listeners registered on this component.
String getName()
Gets the name of the component.
Container getParent()
Gets the parent of this component.
java.awt. getPeer()
peer.Compo Deprecated. As of JDK version 1.1,
nentPeer programs should not directly manipulate peers;
replaced by boolean isDisplayable().
Dimension getPreferredSize()
Gets the preferred size of this component.
PropertyC getPropertyChangeListeners()
hangeListe Returns an array of all the property
ner[] change listeners registered on this component.
Dimension getSize()
Returns the size of this component in the
form of a Dimension object.
Dimension getSize(Dimension rv)
Stores the width/height of this component
into "return value" rv and return rv.
Toolkit getToolkit()
Gets the toolkit of this component.
Object getTreeLock()
Gets this component's locking object (the
object that owns the thread sychronization monitor)
for AWT component-tree and layout operations.
int getWidth()
Returns the current width of this
component.
int getX()
PROGRAMACION CON JAVA 2 367
Returns the current x coordinate of the
components origin.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
setBackground(Color.yellow);
java.lang.Object
|
+--java.awt.GridLayout
Resumén de Constructores
GridLayout()
Creates a grid layout with a default of one column
per component, in a single row.
GridLayout(int rows, int cols)
Creates a grid layout with the specified number of
rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap)
Creates a grid layout with the specified number of
rows and columns.
Resumén de Métodos
void addLayoutComponent(String name, Component comp)
Adds the specified component with the
specified name to the layout.
int getColumns()
Gets the number of columns in this layout.
int getHgap()
Gets the horizontal gap between
components.
int getRows()
Gets the number of rows in this layout.
int getVgap()
Gets the vertical gap between components.
void layoutContainer(Container parent)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
setBackground(Color.yellow);
//uso de GridLayout
setLayout( new GridLayout(2,1));
add(textolabel1);
add(textolabel2);
}
}
java.lang.Object
|
+--java.awt.Component
|
+--java.awt.Button
Resumén de atributos
Resumén de Constructores
Button()
Constructs a Button with no label.
Button(String label)
Constructs a Button with the specified label.
Resumén de Métodos
void addActionListener(ActionListener l)
Adds the specified action listener
to receive action events from this button.
void addNotify()
Creates the peer of the button.
PROGRAMACION CON JAVA 2 387
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated
with this Button.
String getActionCommand()
Returns the command name of the
action event fired by this button.
ActionListener[] getActionListeners()
Returns an array of all the action
listeners registered on this button.
String getLabel()
Gets the label of this button.
EventListener[] getListeners(Class listenerType)
Returns an array of all the objects
currently registered as FooListeners upon this
Button.
protected String paramString()
Returns a string representing the
state of this Button.
protected void processActionEvent(ActionEvent e)
Processes action events occurring
on this button by dispatching them to any
registered ActionListener objects.
protected void processEvent(AWTEvent e)
Processes events on this button.
void removeActionListener(ActionListener l)
Removes the specified action
listener so that it no longer receives action
events from this button.
void setActionCommand(String command)
Sets the command name for the
action event fired by this button.
void setLabel(String label)
Sets the button's label to be the
specified string.
// Archivo: UsoButton.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
setBackground(Color.yellow);
return true;
}
x0 = 400;
y0 = 200;
//dibuja ejes
g.drawLine(0,y0,800,y0);
g.drawLine(x0,0,x0,400);
//dibuja parabola
for(x=-400;x<=400;x++)
390 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
{
angrad=Math.toRadians(x);
y=100*Math.sin(angrad);
//convertir a coordenadas de pantalla
xp=x0+x;
yp=y0-y;
//dibujar punto
g.drawOval((int) xp,(int) yp,2,2);
}
}
x0 = 200;
y0 = 200;
//dibuja ejes
g.drawLine(0,y0,400,y0);
g.drawLine(x0,0,x0,400);
//dibuja parabola
for(x=-300;x<=300;x++)
{
y=x*x;
//convertir a coordenadas de pantalla
xp=(int)(x0+x);
yp=(int)(y0-y);
//dibujar punto
g.drawOval(xp,yp,2,2);
}
El código fuente
this.setLayout(flowLayout1);
this.add(btnOeste, BorderLayout.WEST);
9.9.2. EL PANEL
Poner un panel en la parte inferior y cambiar
su propiedad name
Panel panelBotones = new Panel();
9.9.3. EL APPLET
Situar los siguientes controles sobre el
applet cambiando su propiedad name.
Label titulo=new Label();
Label nombre=new Label();
Label direccion=new Label();
Label pago=new Label();
Label telefono=new Label();
Label ciudad=new Label();
Label provincia=new Label();
textNombre.setColumns(25);
textDireccion.setColumns(25);
textCiudad.setColumns(15);
textProvincia.setColumns(2);
btnPago.setLabel("Comprar");
402 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
btnCancelar.setLabel("Cancelar");
add(componente, constraints);
gbc.anchor=GridBagConstraints.NORTH;
gbc.gridwidth=GridBagConstraints.REMAINDER;
add(titulo, gbc);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.WEST;
gbc.gridwidth=1;
add(nombre, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(textNombre, gbc);
gbc.gridwidth = 1;
add(direccion, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(textDireccion, gbc);
gbc.gridwidth = 1;
add(ciudad, gbc);
add(textCiudad, gbc);
add(provincia, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(textProvincia, gbc);
La quinat fila, está formada por dos
controles: pago y chPago. El código es
semejante, salvo la propiedad fill que toma
el valor NONE antes estaba en HORIZONTAL.
404 A. GAMARRA M. – D. GAMARRA M. – J. GAMARRA M.
Esto hace que el control chPago no ocupe toda
el área disponible, extendiéndose
horizontalmente hasta alinearse con los otros
controles por la parte derecha.
gbc.gridwidth = 1;
add(pago, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill=GridBagConstraints.NONE;
add(chPago, gbc);
gbc.anchor=GridBagConstraints.SOUTH;
add(panelBotones, gbc);
textNombre.setColumns(25);
textDireccion.setColumns(25);
textCiudad.setColumns(15);
textProvincia.setColumns(2);
btnPago.setLabel("Comprar");
btnCancelar.setLabel("Cancelar");
chPago.add("Visa");
chPago.add("MasterCard");
chPago.add("Caja Ahorros");
//gestor gridBaglayout
setLayout(gbl);
gbc.anchor=GridBagConstraints.SOUTH;
gbc.insets=new Insets(15,0,0,0);
add(panelBotones, gbc);
}
}
HILO Y SINCRONIZACIÓN
10.1.2. SINCRONIZACIÓN
Ya que los hilos permiten y potencian el
comportamiento asíncrono de los programas,
debe existir alguna manera de forzar el
sincronismo allí donde sea necesario. Por
ejemplo, si desease que dos hilos se
comunicasen para compartir una estructura de
datos compleja (como una lista enlazada),
necesitará alguna manera de garantizar que
cada uno se aparte del camino del otro. Java
incorpora una versión rebuscada de un modelo
clásico para la sincronización, el monitor.
La mayor parte de los sistemas multihilo
implementan los monitores a modo de objetos,
pero Java proporciona una solución más
elegante: no existe la clase monitor, cada
objeto lleva asociado su propio monitor
implícito, en el que puede entrar sin más que
PROGRAMACION CON JAVA 2 409
hacer una llamada a los métodos synchronized
del objeto. Una vez que el hilo está dentro
del método synchronized, ningún otro hilo
puede efectuar una llamada a otro método
synchronized sobre el mismo objeto.
10.2. THREAD
En Java los hilos se representa mediante una clase. La
clase Thread encapsula todo el control necesario sobre
los hilos. Hay que tomar la precaución de distinguir
claramente un objeto Thread de un hilo en ejecución.
Un objeto Thread se define como el panel de control o
proxy de un hilo en ejecución. En el objeto Thread hay
métodos que controlan si el hilo se está ejecutando,
está durmiendo, en suspenso o detenido. La clase
Thread es la única manera de controlar el
comportamiento de los hilos. En la siguiente
instrucción se muestra como acceder al hilo en
ejecución actual:
Thread t = Thread.currentThread();
10.3. RUNNABLE
Si queremos tener más de un hilo necesitamos crear
otra instancia de Thread. Cuando construimos una nueva
instancia de Thread, necesitamos decirle que código
ejecutar en el nuevo hilo de control. Se puede
comenzar un hilo sobre cualquier objeto que implemente
la interfaz Runnable.
10.5. SINCRONIZACIÓN
Cuando dos o más hilos necesitan acceder de manera
simultánea a un recurso de datos compartido necesitan
asegurarse de que sólo uno de ellos accede al mismo
cada vez. Java proporciona un soporte único, el
monitor, es un objeto que se utiliza como cerrojo
exclusivo. Solo uno de los hilos puede ser el
propietario de un monitor en un instante dado. Los
restantes hilos que estuviesen intentando acceder al
monitor bloqueado quedan en suspenso hasta que el hilo
propietario salga del monitor.
synchronized(objeto) sentencia;
class Callme {
void call (String msg) { * también podía haber puesto
synchronized antes de void *
System.out.print("[" + msg);
try Thread.sleep(1000); catch (Exception e);
System.out.println("]");
}
}
class caller implements Runnable {
String msg;
Callme target;
public caller(Callme t, String s) {
target = t;
msg = s;
new Thread(this).start();
}
public void run() {
synchronized(target) {
target.call(msg);
}
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
new caller(target, "Hola");
new caller(target, "Mundo");
new caller(target, "Sincronizado");
}
}
PROGRAMACION CON JAVA 2 413
Este programa imprime por pantalla el literal "Hola
Mundo Sincronizado", cada palabra en una línea y entre
comillas, se crea una instancia de Callme y tres
instancias de caller que cada una de ellas referencia
al mismo Callme con lo que necesitamos de una
sincronización para el acceso a Callme, pues sino se
mezclarían las tres llamada al haber una sentencia
sleep que retrasa la ejecución de Callme dando lugar a
que antes de que acabe un proceso deje libre el acceso
a dicho objeto.
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if (!valueSet)
try wait(); catch(InterruptedException e);
System.out.println("Obtenido: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if (valueSet)
try wait(); catch(InterruptedException e);
this.n = n;
valueSet = true;
System.out.println("Colocado: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer (Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int y = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
5. Deitel, H. M. y Deitel, P. J.
(1998).”Cómo programar en Java”. Editorial Prentice Hall.
México.