Ejercicios Resueltos Java
Ejercicios Resueltos Java
2
CLASE HOLAMUNDO .......................................................................................... 2
CLASE SUMA ......................................................................................................... 2
CLASE TEST (ejercicio resuelto n 1) ...................................................................... 3
CLASE INTERCAMBIO (ejercicio resuelto n 4)..................................................... 3
CLASE TEST (ejercicio resuelto n 6) ...................................................................... 3
CLASE TEST (ejercicio propuesto n 1) ................................................................... 4
CLASE TEST (ejercicio propuesto n 2) ................................................................... 4
CLASE TEST (ejercicio propuesto n 3) ................................................................... 4
TEMA 2 ....................................................................................................................... 4
CLASES PAJARO Y TEST (apartado 2.3) ............................................................... 4
CLASE PAJARO (apartado 2.6) ............................................................................... 5
CLASE PAJARO (apartado 2.7) ............................................................................... 6
CLASE TEMPERATURA (ejercicio resuelto 1) ....................................................... 6
CLASE PAJARO (ejercicio resuelto 4)..................................................................... 7
CLASE SATELITE (ejercicio resuelto 5).................................................................. 7
CLASE REBAJAS (ejercicio resuelto 6)................................................................... 7
TEMA 3 ....................................................................................................................... 8
CLASE TEST (apartado 3.4)..................................................................................... 8
CLASE LETRAS (ejercicio resuelto 5)..................................................................... 8
CLASE CUENTA (ejercicio resuelto 6).................................................................... 8
CLASE CUENTAINGLES (ejercicio resuelto 7) ...................................................... 9
TEMA 4 ....................................................................................................................... 9
CLASES DEL PAQUETE EDUCACION (apartado 4.1) .......................................... 9
CLASES RECTANGULO Y TESTEOCLONE (apartado 4.2.3)............................. 10
CLASE TEST (apartado 4.3.4)................................................................................ 10
CLASE TESTPARAM (apartado 4.4.1) .................................................................. 11
CLASE RECTANGULO (apartado 4.5.2)............................................................... 11
CLASE TEST (ejercicio resuelto 1a)....................................................................... 12
CLASE TEST (ejercicio resuelto 1b) ...................................................................... 12
CLASE TEST (ejercicio resuelto 2) ........................................................................ 13
CLASE PIRAMIDE (ejercicio resuelto 3)............................................................... 13
CLASE PIRAMIDE (ejercicio resuelto 4)............................................................... 13
CLASE TRANSFORMABASE (ejercicio resuelto 5) ............................................. 14
CLASE BEBE (ejercicio propuesto 9)..................................................................... 14
TEMA 5 ..................................................................................................................... 15
CLASE TEST (apartado 5.1.1)................................................................................ 15
CLASE FECHA (apartado 5.2) ............................................................................... 15
JERARQUIA CLASES (apartado 5.4) .................................................................... 16
JERARQUIA CLASES (apartado 5.5) .................................................................... 16
DIVERSAS CLASES (apartado 5.8)....................................................................... 17
TEMA 6 ..................................................................................................................... 18
CLASE EJEMPLOFLUJOS (apartado 6.2) ............................................................. 18
CLASE EJEMPLOLECTURAPORCONSOLA (Apartado 6.3) ............................. 19
CLASE ESCRITURAPORPANTALLA (Apartado 6.3).......................................... 19
CLASE EJEMPLOPUSHBACKREADER (Ejemplo seccin a fondo)................... 20
CLASE TESTFICHERO (Apartado 6.4.1.1) ........................................................... 20
CLASE TESTFICHERO (Apartado 6.4.1.2) ........................................................... 21
CLASE TESTFICHERO (Apartado 6.4.2) .............................................................. 22
CLASE TESTFICHERO (Apartado 6.4.3) .............................................................. 22
TEMA 1
CLASE HOLAMUNDO
public class holamundo {
/* programa holamundo*/
public static void main(String[] args) {
/* lo nico que hace este programa es mostrar
la cadena "Hola Mundo" por pantalla*/
System.out.println("Hola Mundo");
}
}
CLASE SUMA
class suma
{
static int n1=50; // variable miembro de la clase
public static void main(String [] args)
{
int n2=30, suma=0; // variables locales
suma=n1+n2;
TEMA 2
CLASES PAJARO Y TEST (apartado 2.3)
class pajaro
}
class test
{
public static void main(String[] args) {
pajaro p;
p=new pajaro();
p.setedad(5);
p.printedad();
}
}
TEMA 3
CLASE TEST (apartado 3.4)
class Test
{
public static void main(String [] args)
{
int a=10, b=0, c;
try{
c=a/b;
}
catch(ArithmeticException e){
System.out.println("Error: "+e.getMessage());
return;
}
System.out.println("Resultado:"+c);
}
}
}
}
}
TEMA 4
CLASES DEL PAQUETE EDUCACION (apartado 4.1)
//** Inicio cdigo****
package Utilidades.educacion;
import java.io.*;
public class saludar{
public void saludo(){
System.out.println("Hola");
}
}
//** Fin cdigo****
//** Inicio cdigo****
package Utilidades.educacion;
import java.io.*;
public class despedirse{
public void despedida(){
System.out.println("Adios");
}
}
public static void main(String[] args) {
dato++; // Esto da error al compilar
datostatico++;
metodostatico();
metodo(); // Esto da error al compilar
}
}
return this;
}
}
int numfilas = 4;
for (int i=1; i<(numfilas+1) ; i++){
for (int e=0; e<(numfilas - i);e++)System.out.print(" ");
for (int j=1; j<(2*numfilas+1) ; j++){
int dato = elemento(i,j);
if (dato > 0 ) System.out.print(dato+" ");
}
System.out.println("");
}
}
}
TEMA 5
CLASE TEST (apartado 5.1.1)
class test {
public static void main(String[] args) {
Integer i1 = new Integer(5);
Integer i2 = new Integer("7");
String s1 = i1.toString();
System.out.println(s1);//muestra 5 por pantalla
int i3 = Integer.parseInt("10",10);
int i4 = Integer.parseInt("10",8);
int i5 = Integer.parseInt("BABA",16);
System.out.println(i3);//muestra 10 por pantalla
System.out.println(i4);//muestra 8 por pantalla
System.out.println(i5);//muestra 47.802 por pantalla
System.out.println(Integer.toOctalString(i4));//muestra 10 por pantalla
System.out.println(Integer.toHexString(i5));//muestra baba por pantalla
int i6 = Integer.valueOf("22").intValue();
System.out.println(i6);//muestra 22 por pantalla
}
}
System.out.print("-");
System.out.print(c.get(Calendar.MONTH)+1);
System.out.print("-");
System.out.println(c.get(Calendar.YEAR));
}
}
class padre{
protected int dato1, dato2;
padre(int x,int y){dato1 = x; dato2 = y;}
padre(){
this(5,5);
}
}
class hijo extends padre{
private int dato1, dato2;
hijo(int x,int y){
super(2,2);
dato1 = x;
dato2 = y;
}
hijo(){
dato1 = 3;
dato2 = 3;
}
public void getDato(){
System.out.println("Padre dato1:" + super.dato1);
System.out.println("Padre dato2:" + super.dato2);
System.out.println("hijo dato1:" + this.dato1);
System.out.println("hijo dato2:" + this.dato2);
}
}
class test {
public static void main(String[] args) {
hijo h1 = new hijo(1,1);
h1.getDato();
hijo h2 = new hijo();
h2.getDato();
}
}
TEMA 6
CLASE EJEMPLOFLUJOS (apartado 6.2)
import java.io.*;
public class EjemploFlujos
{
public static void main(String[] args)
{
String s = new String("En un lugar de la mancha de cuyo nombre no quiero
acordarme, ");
s = s + "no ha mucho tiempo que viva un hidalgo de los de lanza en astillero, ";
s = s + "adarga antigua, rocn flaco y galgo corredor...";
char[] arr = new char[s.length()];
int car = 0;
StringReader flujoInput = new StringReader(s);
flujoOutput = new CharArrayWriter();
try
{
while ((car = flujoInput.read()) != -1){
flujoOutput.write(car);
}
arr = flujoOutput.toCharArray();
System.out.println(arr);
}
catch (IOException e) {
e.printStackTrace();
}
finally
{
flujoInput.close();
flujoOutput.close();
}
}
}
pantalla.write(array, 0, 6);
pantalla.println("");
pantalla.flush();
}
}
char c=0;
try{
f=new FileOutputStream("datos.txt");
for (int i=0; i<s.length();i++){
c=s.charAt(i);
f.write((byte)c);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
f.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
l = d.readLong();
System.out.println(l);
}
}
}catch (EOFException eof) {
System.out.println(" --------------------------");
}catch (FileNotFoundException fnf) {
System.err.println("Fichero no encontrado " + fnf);
}catch(IOException e){
System.err.println("Se ha producido una IOException");
e.printStackTrace();
}catch (Throwable e) {
System.err.println("Error de programa: " + e);
e.printStackTrace();
}finally{
if (d != null) {
d.close();
fe.close();
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
acciones(e);
}
});
frame.getContentPane().add(label);
frame.getContentPane().add(btnlimpia);
frame.getContentPane().add(btnescribe);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setLayout(new GridLayout(0,1));
frame.pack();
frame.setVisible(true);
}
}
acciones(e);
}
});
frame.getContentPane().add(label);
frame.getContentPane().add(btnlimpia);
frame.getContentPane().add(btnescribe);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setLayout(new GridLayout(0,1));
frame.pack();
frame.setVisible(true);
}
}
txtdolar.setText(String.valueOf(icambio));
//cambiar los slider
sliderdolar.setValue(Math.round(Float.parseFloat(txtdolar.getText())));
slidereuro.setValue(Math.round(Float.parseFloat(txteuro.getText())));
}
if ( e.getSource() == txtdolar ){
System.out.println("dentro");
float icambio=Float.parseFloat(txtdolar.getText());
icambio=100*icambio/Float.parseFloat(txtcambio.getText());
icambio = Math.round(icambio);
icambio = icambio/100;
txteuro.setText(String.valueOf(icambio));
}
}
public static void mueveSlider(ChangeEvent e) {
int valor;
JSlider obj=(JSlider)e.getSource();
System.out.println(obj.getValueIsAdjusting());
System.out.println(obj.getValue());
if (!obj.getValueIsAdjusting()) {
System.out.println(obj.getValue());
valor = (int)obj.getValue();
if (obj == sliderdolar){
txtdolar.setText(String.valueOf(valor));
float
icambio=100*valor/Float.parseFloat(txtcambio.getText());
icambio=Math.round(icambio);
icambio=icambio/100;
//cambiar el txteuro
txteuro.setText(String.valueOf(icambio));
//cambiar el slidereuro
int i = Math.round(icambio);
slidereuro.setValue(i);
}
if (obj == slidereuro){
txteuro.setText(String.valueOf(valor));
float
icambio=100*valor*Float.parseFloat(txtcambio.getText());
icambio=Math.round(icambio);
icambio=icambio/100;
//cambiar el txtdolar
txtdolar.setText(String.valueOf(icambio));
//cambiar el sliderdolar
int i = Math.round(icambio);
slidereuro.setValue(i);
}
}
}
public static void colocaelementos(){
frame.getContentPane().add(panel1);
frame.getContentPane().add(panel2);
frame.getContentPane().add(panel3);
slidereuro.setBorder(BorderFactory.createTitledBorder("Euros"));
slidereuro.setMajorTickSpacing(200);
slidereuro.setMinorTickSpacing(100);
slidereuro.setPaintTicks(true);
slidereuro.setPaintLabels(true);
slidereuro.disable();
sliderdolar.setBorder(BorderFactory.createTitledBorder("Dolares"));
sliderdolar.setMajorTickSpacing(200);
sliderdolar.setMinorTickSpacing(100);
sliderdolar.setPaintTicks(true);
sliderdolar.setPaintLabels(true);
sliderdolar.disable();
panel1.add(lbleuros);
panel1.add(txteuro);
panel1.add(slidereuro);
panel2.add(label);
panel2.add(txtcambio);
panel3.add(lbldolares);
panel3.add(txtdolar);
panel3.add(sliderdolar);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
txteuro.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cambiotexto(e);
}
});
txtdolar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cambiotexto(e);
}
});
frame.setLayout(new FlowLayout());
panel1.setLayout(new GridLayout(0,1));
panel2.setLayout(new GridLayout(0,1));
panel3.setLayout(new GridLayout(0,1));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) { }
colocaelementos();
}
}
TEMA 7
CLASE TEMPERATURAS (Apartado 7.1.5)
public class temperaturas {
private static int[] temperaturas1;
final static int POS=10; //nmero de posiciones del array
public static void main(String[] args) {
int dato=0;
int media=0;
temperaturas1 = new int[POS];
for (int i=0;i<POS;i++){ //leer los valores de temperatura
try{
System.out.println("Introduzca Temperatura:");
String sdato = System.console().readLine();
dato = Integer.parseInt(sdato);
}catch(Exception e){
System.out.println("Error en la introduccin de datos");
}
temperaturas1[i]=dato;
}
for (int i=0;i<POS;i++){//hacer la media
media = media + temperaturas1[i];
}
media = media / POS;
System.out.println("La media de temperaturas es "+media);
}
}
TEMA 8
Creando Tablas con JDBC (Apartado 8.4.1)
public static void createEQUIPO(Connection con, String BDNombre) throws SQLException {
String createString = "create table " + BDNombre + ".EQUIPO " +
"(TEAM_ID integer NOT NULL," +
"EQ_NOMBRE varchar(40) NOT NULL," +
"ESTADIO varchar(40) NOT NULL," +
"POBLACION varchar(20) NOT NULL," +
"PROVINCIA varchar(20) NOT NULL," +
"COD_POSTAL char(5)," +
"PRIMARY KEY (TEAM_ID))";
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
} catch (SQLException e) {
printSQLException(e);
} finally {
stmt.close();
}
}
public static void createJUGADORES(Connection con, String BDNombre) throws SQLException
{
String createString = "create table " + BDNombre + ".JUGADORES" +
"(PLAYER_ID integer NOT NULL," +
"TEAM_ID integer NOT NULL," +
"NOMBRE varchar(40) NOT NULL," +
"DORSAL integer NOT NULL," +
"EDAD integer NOT NULL," +
"PRIMARY KEY (PLAYER_ID)," +
"FOREIGN KEY (TEAM_ID) REFERENCES EQUIPO (TEAM_ID))";
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
} catch (SQLException e) {
printSQLException(e);
} finally {
stmt.close();
}
}
TEMA 9
CLASE ALUMNO (Apartado 9.5)
public class alumno{
private String nombre;
private int edad;
private double nota;
public alumno(){
this.nombre = null;
edad = 0;
nota = 0;
}
public alumno(String n,int e) {
this.nombre = n;
this.edad = e;
this.nota = -1; //nota no establecida
}
public alumno(String nom,int e, double not) {
this.nombre = nom;
this.edad = e;
this.nota = not;
}
public void setNombre(String n) {
this.nombre = n;
}
public String getNombre() {
return this.nombre;
}
public void setNota(double n) {
this.nota=n;
}
public double getNota() {
return this.nota;
}
public void setEdad(int e) {
this.edad=e;
}
public int getEdad() {
return this.edad;
}
public String toString() {
if (this.nota != -1)
return this.nombre+"("+this.edad+") Nota:"+this.nota;
return this.nombre+"("+this.edad+")";
}
}
new File("alumnos.db4o").delete();
ObjectContainer bd = Db4oEmbedded.openFile(Db4oEmbedded
.newConfiguration(), "alumnos.db4o");
try {
almacenarAlumnos(bd);
consultaSODA(bd);
} catch(Exception e){
e.printStackTrace();
}finally {
bd.close();
}
}
public static void mostrarResultado(ObjectSet res){
System.out.println("Recuperados "+res.size()+" Objetos");
while(res.hasNext()) {
System.out.println(res.next());
}
}
public static void almacenarAlumnos(ObjectContainer bd) {
alumno a1 = new alumno("Juan Gmez",23,8.75);
bd.store(a1);
System.out.println(a1.getNombre()+" Almacenado");
alumno a2 = new alumno("Emilio Anaya",24,6.25);
bd.store(a2);
System.out.println(a2.getNombre()+" Almacenado");
alumno a3 = new alumno("Angeles Blanco",26,7);
bd.store(a3);
System.out.println(a3.getNombre()+" Almacenado");
}
public static void consultaSODA(ObjectContainer bd) {
Query query=bd.query();
query.constrain(alumno.class);
Constraint constr=query.descend("nota").constrain(7).smaller();
query.descend("edad").constrain(25).greater().or(constr);
ObjectSet result=query.execute();
mostrarResultado(result);
}
}
this.descripcion=descripcion;
this.al=null;
}
public alumno getAlumno() {
return al;
}
public void setAlumno(alumno a) {
this.al = a;
}
public String getDescripcion() {
return descripcion;
}
public String toString(){
return descripcion + "-> "+ al;
}
}
mostrarTodosProyectos(bd);
mostrarTodosAlumnos(bd);
} catch(Exception e){
e.printStackTrace();
}finally {
bd.close();
}
}
public static void mostrarResultado(ObjectSet res){
System.out.println("Recuperados "+res.size()+" Objetos");
while(res.hasNext()) {
System.out.println(res.next());
}
}
public static void almacenarProyectos(ObjectContainer bd) {
proyecto p1 = new proyecto("Robot con microcontroladores");
alumno a1 = new alumno("Juan Gmez",23,8.75);
p1.setAlumno(a1);
bd.store(p1);
System.out.println(p1.toString()+" Almacenado");
proyecto p2 = new proyecto("Webmin sobre Ubuntu");
alumno a2 = new alumno("Emilio Anaya",24,6.25);
p2.setAlumno(a2);
bd.store(p2);
System.out.println(p2.toString()+" Almacenado");
proyecto p3 = new proyecto("Joomla y Drupal");
alumno a3 = new alumno("Angeles Blanco",26,7);
p3.setAlumno(a3);
bd.store(p3);
System.out.println(p3.toString()+" Almacenado");
proyecto p4 = new proyecto("Doctor Profiler");
alumno a4 = new alumno("Luis Alberto Garca",29,9.5);
p4.setAlumno(a4);
bd.store(p4);
System.out.println(p4.toString()+" Almacenado");
}
public static void mostrarTodosAlumnos(ObjectContainer bd) {
Query query=bd.query();
query.constrain(alumno.class);
ObjectSet result=query.execute();
mostrarResultado(result);
}
public static void mostrarTodosProyectos(ObjectContainer bd) {
Query query=bd.query();
query.constrain(proyecto.class);
ObjectSet result=query.execute();
mostrarResultado(result);
}
public static void borraPorDescripcion(ObjectContainer bd) {
Query query=bd.query();
query.constrain(proyecto.class);
query.descend("descripcion").constrain("Doctor Profiler");
ObjectSet result=query.execute();
while(result.hasNext()) {
proyecto p= (proyecto)result.next();
System.out.println("Borrado: "+p);
bd.delete(p);
}
}
}