Hola a todos, hoy os dejo una serie de ejercicios propuestos y resueltos Java de backtraking.
Todos los ejercicios que proponemos están resueltos en este mismo post, intenta hacerlo por ti mismo y si te quedas atascado puedes mirar la solución. Recuerda, que no tiene por que estar igual tu solución con la del post, el objetivo es que aprendas no que me copies la solución.
Te recomiendo que uses mensajes de trazas, donde te sean necesarios. Si tienes problemas también puedes usar el depurador.
Aquí tienes todos los posts relacionados con Java:
1. Crea una clase llamada HiloNumerosLetras que implemente runnable y tenga de atributo un numero llamado tipo.
Si el tipo es 1, mostrara los numeros del 1 al 30
Si el tipo es 2, mostrara las letras de la ‘a’ a la ‘z’.
HiloNumeroLetras.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package ejercicio_thread_ddr_1; public class HiloNumeroLetras implements Runnable{ //Atributos private int tipo; //Constructor public HiloNumeroLetras(int tipo) { this.tipo = tipo; } @Override public void run() { //Bucle infinito while (true) { //Segun el tipo hace una u otra cosa switch (tipo) { case 1: //numeros for (int i = 1; i < 30; i++) { System.out.println(i); } break; case 2: //letras for (char c = 'a'; c < 'z'; c++) { System.out.println(c); } break; } } } } |
Ejercicio_thread_DDR_1.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package ejercicio_thread_ddr_1; public class Ejercicio_thread_DDR_1 { public static void main(String[] args) { HiloNumeroLetras h1 = new HiloNumeroLetras(1); HiloNumeroLetras h2 = new HiloNumeroLetras(2); Thread t1 = new Thread(h1); Thread t2 = new Thread(h2); t1.start(); t2.start(); } } |
2. Crea una clase llamada Contador que contenga un atributo que sea un contador,
otro que sea el nombre del hilo y otro que sea el limite del contador, es decir, donde debe acabar.
Crea varios contadores y ejecútalos.
Contador.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package ejercicio_thread_ddr_2; public class Contador implements Runnable { //Atributos private int contador; private String nombre; private int limite; //Constructor public Contador(String nombre, int limite) { this.contador = 0; this.nombre = nombre; this.limite = limite; } @Override public void run() { //Recorremos los numeros while (contador <= limite) { System.out.println("Hilo " + nombre + ": " + contador); contador++; } //fin de hilo System.out.println("Hilo " + nombre + " ya ha acaado"); } } |
Ejercicio_thread_DDR_2.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package ejercicio_thread_ddr_2; import java.util.logging.Level; import java.util.logging.Logger; public class Ejercicio_thread_DDR_2 { public static void main(String[] args) { //Creamos los objetos Contador c1 = new Contador("Contador 1", 40); Contador c2 = new Contador("Contador 2", 50); Contador c3 = new Contador("Contador 3", 20); Contador c4 = new Contador("Contador 4", 70); //Creamos los hilos Thread t1 = new Thread(c1); Thread t2 = new Thread(c2); Thread t3 = new Thread(c3); Thread t4 = new Thread(c4); //Iniciamos los hilos t1.start(); t2.start(); t3.start(); t4.start(); //Esperamos a que acaben los hilos try { t1.join(); t2.join(); t3.join(); t4.join(); } catch (InterruptedException ex) { Logger.getLogger(Ejercicio_thread_DDR_2.class.getName()).log(Level.SEVERE, null, ex); } //Fin System.out.println("Fin del programa"); } } |
3. Haz una ventana de un reloj digital. Te muestro un ejemplo:

RelojDigital.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
package ejercicio_thread_ddr_3; import java.util.Observable; import java.util.logging.Level; import java.util.logging.Logger; public class RelojDigital extends Observable implements Runnable { private int horas, minutos, segundos; public RelojDigital(int horas, int minutos, int segundos) { this.horas = horas; this.minutos = minutos; this.segundos = segundos; } @Override public void run() { String tiempo; try { while (true) { tiempo = ""; if (horas < 10) { tiempo += "0" + horas; } else { tiempo += horas; } tiempo += ":"; if (minutos < 10) { tiempo += "0" + minutos; } else { tiempo += minutos; } tiempo += ":"; if (segundos < 10) { tiempo += "0" + segundos; } else { tiempo += segundos; } this.setChanged(); this.notifyObservers(tiempo); this.clearChanged(); Thread.sleep(1000); segundos++; if (segundos == 60) { minutos++; segundos = 0; if (minutos == 60) { minutos = 0; horas++; if (horas == 24) { horas = 0; } } } } } catch (InterruptedException ex) { Logger.getLogger(RelojDigital.class.getName()).log(Level.SEVERE, null, ex); } } } |
FrmContador.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
package ejercicio_thread_ddr_3; import java.util.Observable; import java.util.Observer; public class FrmContador extends javax.swing.JFrame implements Observer{ public FrmContador() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { lblCronometro = new javax.swing.JLabel(); btnIniciar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Reloj digital"); lblCronometro.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N btnIniciar.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N btnIniciar.setText("Iniciar"); btnIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIniciarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(lblCronometro, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCronometro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// //GEN-END:initComponents private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed this.btnIniciar.setEnabled(false); RelojDigital r = new RelojDigital(23, 59, 50); r.addObserver(this); Thread t = new Thread(r); t.start(); }//GEN-LAST:event_btnIniciarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmContador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmContador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmContador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmContador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmContador().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnIniciar; private javax.swing.JLabel lblCronometro; // End of variables declaration//GEN-END:variables @Override public void update(Observable o, Object arg) { lblCronometro.setText((String) arg); } } |
4. Haz una ventana con 4 progressbar, se crearan 4 hilos que representaran a caballos (que tienen un nombre y un camino recorrido o porcentaje recorrido). Al pulsar el botón de iniciar se empezará a avanzar, actualizando los progressbar con un numero aleatorio entre 1 y 15.
Gana el primero que llegue a 100.

FrmCarrera.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
package ejercicio_thread_ddr_4; import java.util.Observable; import java.util.Observer; public class FrmCarrera extends javax.swing.JFrame implements Observer { private Thread[] hilos; public FrmCarrera() { initComponents(); hilos = new Thread[4]; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { pg1 = new javax.swing.JProgressBar(); jLabel1 = new javax.swing.JLabel(); pg2 = new javax.swing.JProgressBar(); jLabel2 = new javax.swing.JLabel(); pg3 = new javax.swing.JProgressBar(); jLabel3 = new javax.swing.JLabel(); pg4 = new javax.swing.JProgressBar(); jLabel4 = new javax.swing.JLabel(); btnIniciar = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); lblGanador = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); pg1.setStringPainted(true); jLabel1.setText("Caballo 1"); pg2.setStringPainted(true); jLabel2.setText("Caballo 2"); pg3.setStringPainted(true); jLabel3.setText("Caballo 3"); pg4.setStringPainted(true); jLabel4.setText("Caballo 4"); btnIniciar.setText("Iniciar"); btnIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIniciarActionPerformed(evt); } }); jLabel5.setText("El ganador es: "); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(pg1, javax.swing.GroupLayout.PREFERRED_SIZE, 533, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(pg2, javax.swing.GroupLayout.PREFERRED_SIZE, 533, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(pg3, javax.swing.GroupLayout.PREFERRED_SIZE, 533, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(pg4, javax.swing.GroupLayout.PREFERRED_SIZE, 533, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btnIniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 595, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(225, 225, 225) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblGanador, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(19, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel1)) .addComponent(pg1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel2)) .addComponent(pg2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel3)) .addComponent(pg3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel4)) .addComponent(pg4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblGanador, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(btnIniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34)) ); pack(); }// //GEN-END:initComponents private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed this.btnIniciar.setEnabled(false); this.lblGanador.setText(""); for (int i = 0; i < hilos.length; i++) { Caballo c = new Caballo((i+1)+""); c.addObserver(this); hilos[i] = new Thread(c); hilos[i].start(); } }//GEN-LAST:event_btnIniciarActionPerformed private void terminar(){ for (int i = 0; i < hilos.length; i++) { hilos[i].interrupt(); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmCarrera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmCarrera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmCarrera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmCarrera.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmCarrera().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnIniciar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel lblGanador; private javax.swing.JProgressBar pg1; private javax.swing.JProgressBar pg2; private javax.swing.JProgressBar pg3; private javax.swing.JProgressBar pg4; // End of variables declaration//GEN-END:variables @Override public void update(Observable o, Object arg) { Caballo c = (Caballo) o; int porcentaje = (int) arg; switch (c.getNombre()) { case "1": this.pg1.setValue(porcentaje); break; case "2": this.pg2.setValue(porcentaje); break; case "3": this.pg3.setValue(porcentaje); break; case "4": this.pg4.setValue(porcentaje); break; } if(porcentaje>=100){ terminar(); this.btnIniciar.setEnabled(true); this.lblGanador.setText("Caballo "+c.getNombre()); } } } |
Caballo.java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package ejercicio_thread_ddr_4; import java.util.Observable; import java.util.logging.Level; import java.util.logging.Logger; public class Caballo extends Observable implements Runnable { private String nombre; public Caballo(String nombre) { this.nombre = nombre; } public String getNombre() { return nombre; } @Override public void run() { int porcentaje = 0; int numAleatorio; try { while (porcentaje < 100) { numAleatorio = generaNumeroAleatorio(1, 15); System.out.println("Caballo " + nombre + " ha aumentado en " + numAleatorio); porcentaje += numAleatorio; this.setChanged(); this.notifyObservers(porcentaje); this.clearChanged(); Thread.sleep(1000); } } catch (InterruptedException ex) { System.out.println("Hilo interrumpido"); } } public static int generaNumeroAleatorio(int minimo, int maximo) { int num = (int) Math.floor(Math.random() * (maximo - minimo + 1) + (minimo)); return num; } } |
Espero que os sea de ayuda.
Tengo dudas
leer datos
Leer los datos de las ventas que se realizan al concesionario, las que provienen de una secuencia de números naturales leída desde teclado. Los valores leídos corresponden a los códigos de los clientes del concesionario. La secuencia termina en 0, valor que no hay que tener en cuenta como código de cliente.
Hacer un algoritmo llamado LlegirDades que lea estos datos, las guarde en un array y, a continuación, obtenga el código del cliente que aparece más veces (aquel al que se han vendido más coches). Si hay más de un cliente que es el más repetido, indicar el primero que se encuentre.
Hay que tener presente que el número máximo de valores que se pueden almacenar es 1.000.
Considera que estás desarrollando una web para una empresa que fabrica motores
(suponemos que se trata del tipo de motor de una bomba para mover fluidos).
Definir una variable tipoMotor y permitir que el usuario ingrese un valor entre 1 y 4.
El programa debe mostrar lo siguiente:
o Si el tipo de motor es 1, mostrar un mensaje indicando “La bomba es una
bomba de agua”.
o Si el tipo de motor es 2, mostrar un mensaje indicando “La bomba es una
bomba de gasolina”.
o Si el tipo de motor es 3, mostrar un mensaje indicando “La bomba es una
bomba de hormigón”.
o Si el tipo de motor es 4, mostrar un mensaje indicando “La bomba es una
bomba de pasta alimenticia”.
o Si no se cumple ninguno de los valores anteriores mostrar el mensaje “No
existe un valor válido para tipo de bomba”