mirror of
https://gitlab.com/tutorial-java-rafa-munoz/tutorial-java-2024-25/tutorialjava2024-25.git
synced 2025-11-09 09:57:40 +01:00
feat(ch 6 & 7): ex solved
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package tutorialJava.capitulo6_ColeccionesDeDatos.ejercicios.bloque02_Hashmap;
|
||||
|
||||
public class Articulo {
|
||||
|
||||
private String nombre;
|
||||
private int codigoDeBarras;
|
||||
private int numeroDeEstante;
|
||||
private int stock;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public Articulo() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param nombre
|
||||
* @param codigoDeBarras
|
||||
* @param numeroDeEstante
|
||||
* @param stock
|
||||
*/
|
||||
public Articulo(String nombre, int codigoDeBarras, int numeroDeEstante, int stock) {
|
||||
super();
|
||||
this.nombre = nombre;
|
||||
this.codigoDeBarras = codigoDeBarras;
|
||||
this.numeroDeEstante = numeroDeEstante;
|
||||
this.stock = stock;
|
||||
}
|
||||
|
||||
public String getNombre() {
|
||||
return nombre;
|
||||
}
|
||||
public void setNombre(String nombre) {
|
||||
this.nombre = nombre;
|
||||
}
|
||||
public int getCodigoDeBarras() {
|
||||
return codigoDeBarras;
|
||||
}
|
||||
public void setCodigoDeBarras(int codigoDeBarras) {
|
||||
this.codigoDeBarras = codigoDeBarras;
|
||||
}
|
||||
public int getNumeroDeEstante() {
|
||||
return numeroDeEstante;
|
||||
}
|
||||
public void setNumeroDeEstante(int numeroDeEstante) {
|
||||
this.numeroDeEstante = numeroDeEstante;
|
||||
}
|
||||
public int getStock() {
|
||||
return stock;
|
||||
}
|
||||
public void setStock(int stock) {
|
||||
this.stock = stock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Articulo [nombre=" + nombre + ", codigoDeBarras=" + codigoDeBarras + ", numeroDeEstante="
|
||||
+ numeroDeEstante + ", stock=" + stock + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -24,3 +24,16 @@ public class Ejemplo05_Recursividad_Factorial {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque01_WrappersDeTiposPrimitivos;
|
||||
|
||||
public class Ejercicio01_TablaConCaracteristicasDeTiposPrimitivos {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Características de un Integer
|
||||
System.out.println("Valor máximo para un Integer: " + Integer.MAX_VALUE);
|
||||
System.out.println("Valor mínimo para un Integer: " + Integer.MIN_VALUE);
|
||||
System.out.println("Tamaño en bits complemento a 2 para Integer: " + Integer.SIZE);
|
||||
|
||||
// Características de un Long
|
||||
System.out.println("\nValor máximo para un Long: " + Long.MAX_VALUE);
|
||||
System.out.println("Valor mínimo para un Long: " + Long.MIN_VALUE);
|
||||
System.out.println("Tamaño en bits complemento a 2 para Long: " + Long.SIZE);
|
||||
|
||||
// Características de un Short
|
||||
System.out.println("\nValor máximo para un Short: " + Short.MAX_VALUE);
|
||||
System.out.println("Valor mínimo para un Short: " + Short.MIN_VALUE);
|
||||
System.out.println("Tamaño en bits complemento a 2 para Short: " + Short.SIZE);
|
||||
|
||||
// Características de un Float
|
||||
System.out.println("\nValor máximo para un Float: " + Float.MAX_VALUE);
|
||||
System.out.println("Valor mínimo para un Float: " + Float.MIN_VALUE);
|
||||
System.out.println("Tamaño en bits complemento a 2 para Float: " + Float.SIZE);
|
||||
|
||||
// Características de un Double
|
||||
System.out.println("\nValor máximo para un Double: " + Double.MAX_VALUE);
|
||||
System.out.println("Valor mínimo para un Double: " + Double.MIN_VALUE);
|
||||
System.out.println("Tamaño en bits complemento a 2 para Double: " + Double.SIZE);
|
||||
|
||||
// Wrapper para el tipo de datos "Character"
|
||||
System.out.println("Tamaño en bits complemento a 2 para Character: " + Character.SIZE);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque01_WrappersDeTiposPrimitivos;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Ejercicio02_PedirPasswordConRequisitos {
|
||||
|
||||
public static void main(String[] args) {
|
||||
boolean mayuscula = false;
|
||||
boolean minuscula = false;
|
||||
boolean digito = false;
|
||||
boolean noAlfanumerico = false;
|
||||
Scanner sc = new Scanner(System.in);
|
||||
|
||||
do {
|
||||
mayuscula = false;
|
||||
minuscula = false;
|
||||
digito = false;
|
||||
noAlfanumerico = false;
|
||||
|
||||
System.out.println("Dame una contraseña con mayúsculas, minúsculas, dígitos y algún carácter no alfanumérico: ");
|
||||
String password = sc.next();
|
||||
|
||||
for (int i = 0; i < password.length(); i++) {
|
||||
if (Character.isUpperCase(password.charAt(i))) {
|
||||
mayuscula = true;
|
||||
}
|
||||
if (Character.isLowerCase(password.charAt(i))) {
|
||||
minuscula = true;
|
||||
}
|
||||
if (Character.isDigit(password.charAt(i))) {
|
||||
digito = true;
|
||||
}
|
||||
if (!Character.isLetterOrDigit(password.charAt(i))) {
|
||||
noAlfanumerico = true;
|
||||
}
|
||||
}
|
||||
} while (!(mayuscula && minuscula && digito && noAlfanumerico));
|
||||
|
||||
// Contraseña establecida
|
||||
System.out.println("Contraseña establecida :-)");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque01_WrappersDeTiposPrimitivos;
|
||||
|
||||
public class Ejercicio03_100PrimerosNumerosEnHexadecimal {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
for (int i = 0; i < 101; i++) {
|
||||
System.out.println("Decimal: " + i + " - Hexadecimal: 0x" + Integer.toHexString(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Ejemplo de comentario en fichero de propiedades
|
||||
|
||||
# Propiedades
|
||||
USUARIO=RafaelMunoz77
|
||||
PASSWORD=1<EFBFBD>DAWlosmejores
|
||||
ID_USUARIO=1523
|
||||
TODO_CORRECTO=true
|
||||
@@ -0,0 +1,95 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque01_WrappersDeTiposPrimitivos;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
|
||||
|
||||
public class Ejercicio04_LecturaFicheroPropiedades {
|
||||
private static Properties propiedades = null;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static Properties getPropiedades() {
|
||||
if (propiedades == null) {
|
||||
propiedades = new Properties();
|
||||
|
||||
try {
|
||||
// Otra forma de leer el fichero de propiedades
|
||||
File file = new File("./src/tutorialJava/capitulo7_Recursos/ejercicios/bloque01_WrappersDeTiposPrimitivos/Ejercicio04.properties");
|
||||
System.out.println("Fichero encontrado: " + file.exists());
|
||||
propiedades.load(new FileReader(file));
|
||||
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
return propiedades;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param nombrePropiedad
|
||||
* @return
|
||||
*/
|
||||
public static String getProperty(String nombrePropiedad) {
|
||||
return getPropiedades().getProperty(nombrePropiedad);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param nombrePropiedad
|
||||
* @return
|
||||
*/
|
||||
public static int getIntProperty (String nombrePropiedad) {
|
||||
return Integer.parseInt(getPropiedades().getProperty(nombrePropiedad));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param nombrePropiedad
|
||||
* @return
|
||||
*/
|
||||
public static Float getFloatProperty (String nombrePropiedad) {
|
||||
return Float.parseFloat(getPropiedades().getProperty(nombrePropiedad));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param nombrePropiedad
|
||||
* @return
|
||||
*/
|
||||
public static Boolean getBooleanProperty (String nombrePropiedad) {
|
||||
return Boolean.parseBoolean(getPropiedades().getProperty(nombrePropiedad));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main (String args[]) {
|
||||
String usuario = Ejercicio04_LecturaFicheroPropiedades.getProperty("USUARIO");
|
||||
String password = Ejercicio04_LecturaFicheroPropiedades.getProperty("PASSWORD");
|
||||
int id = Ejercicio04_LecturaFicheroPropiedades.getIntProperty("ID_USUARIO");
|
||||
boolean todoCorrecto = Ejercicio04_LecturaFicheroPropiedades.getBooleanProperty("TODO_CORRECTO");
|
||||
|
||||
System.out.println("Usuario leído del fichero de propiedades: " + usuario);
|
||||
System.out.println("Password leído del fichero de propiedades: " + password);
|
||||
System.out.println("Id de usuario leído del fichero de propiedades: " + id);
|
||||
System.out.println("Todo correcto: " + todoCorrecto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque02_MathDateCalendar;
|
||||
|
||||
public class Ejercicio01_PuntoDeCorteDeDosGraficas {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
double x = 0, y1 = 0, y2 = 0;
|
||||
|
||||
for (x = 0; x < 1; x+=0.0001) {
|
||||
y1 = Math.sqrt(x);
|
||||
y2 = - Math.log(x);
|
||||
|
||||
if (Math.abs(y1 - y2) < 0.001) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("Cruce encontrado en x: " + x + " y: " + ((y1 + y2) / 2f));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque02_MathDateCalendar;
|
||||
|
||||
public class Ejercicio02_PI_SeriesInfinitas_GregoryLeibniz {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
double PI = 0;
|
||||
int signo = 1;
|
||||
int denominador = 1;
|
||||
|
||||
while (Math.abs(Math.PI - PI) > 0.00001) {
|
||||
PI += signo * (4f / denominador);
|
||||
signo = -signo;
|
||||
denominador += 2;
|
||||
}
|
||||
|
||||
System.out.println("PI: " + PI);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque02_MathDateCalendar;
|
||||
|
||||
public class Ejercicio03_Hipotenusa {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("Hipotenusa de un triángulo rectángulo con catetos 4 y 5cm: " +
|
||||
Math.hypot(4, 5));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque02_MathDateCalendar;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Scanner;
|
||||
|
||||
import javax.swing.JOptionPane;
|
||||
|
||||
public class Ejercicio04_DateCalendar {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Date date = pideFechaConFormat("dd/MM/yyyy");
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeInMillis(date.getTime());
|
||||
|
||||
System.out.println("Año del date: " + new SimpleDateFormat("yyyy").format(date));
|
||||
System.out.println("Mes del date: " + new SimpleDateFormat("MMM").format(date));
|
||||
System.out.println("Día del date: " + new SimpleDateFormat("dd").format(date));
|
||||
System.out.println("Hora del date: " + new SimpleDateFormat("HH").format(date));
|
||||
System.out.println("Minuto del date: " + new SimpleDateFormat("mm").format(date));
|
||||
System.out.println("Segundo del date: " + new SimpleDateFormat("ss").format(date));
|
||||
|
||||
System.out.println("\nAño del calendar: " + calendar.get(Calendar.YEAR));
|
||||
System.out.println("Mes del calendar: " + calendar.get(Calendar.MONTH));
|
||||
System.out.println("Día del calendar: " + calendar.get(Calendar.DAY_OF_MONTH));
|
||||
System.out.println("Hora del calendar: " + calendar.get(Calendar.HOUR_OF_DAY));
|
||||
System.out.println("Minuto del calendar: " + calendar.get(Calendar.MINUTE));
|
||||
System.out.println("Segundo del calendar: " + calendar.get(Calendar.SECOND));
|
||||
|
||||
calendar.add(Calendar.DAY_OF_YEAR, 3); System.out.println("\nCalendar más 3 días: " + calendar.getTime());
|
||||
calendar.add(Calendar.DAY_OF_YEAR, -14); System.out.println("Calendar menos 2 semanas: " + calendar.getTime());
|
||||
calendar.add(Calendar.DAY_OF_YEAR, 300); System.out.println("Calendar más 300 días: " + calendar.getTime());
|
||||
calendar.add(Calendar.YEAR, 4); System.out.println("Calendar más 4 años: " + calendar.getTime());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param formato
|
||||
* @return
|
||||
*/
|
||||
private static Date pideFechaConFormat (String formato) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(formato);
|
||||
|
||||
do {
|
||||
try {
|
||||
return sdf.parse(JOptionPane.showInputDialog("Introduzca una fecha con formato dd/MM/yyyy: "));
|
||||
} catch (ParseException e) {
|
||||
System.out.println("Fecha con formato incorrecto. Vuelva a intentarlo");
|
||||
}
|
||||
} while (true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque02_MathDateCalendar;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class Ejercicio05_DiferenciaHorariaEntreCiudades {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Calendar ahoraEnRoma = Calendar.getInstance(TimeZone.getTimeZone("Europe/Rome"));
|
||||
Calendar ahoraEnWashington = Calendar.getInstance(TimeZone.getTimeZone("EST"));
|
||||
|
||||
int horaEnRoma = ahoraEnRoma.get(Calendar.HOUR_OF_DAY);
|
||||
int horaEnWashington = ahoraEnWashington.get(Calendar.HOUR_OF_DAY);
|
||||
|
||||
System.out.println("Diferencia horaria entre Roma y Wasington: " + Math.abs(horaEnRoma - horaEnWashington));
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorFraseConPalabraBombilla;
|
||||
|
||||
public class MinimoNumeroDePalabrasNoAlcanzadoException extends Exception {
|
||||
|
||||
private int minimoNumeroPalabras;
|
||||
|
||||
public MinimoNumeroDePalabrasNoAlcanzadoException(int minimoNumeroPalabras) {
|
||||
this.minimoNumeroPalabras = minimoNumeroPalabras;
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public MinimoNumeroDePalabrasNoAlcanzadoException(String message) {
|
||||
super(message);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public MinimoNumeroDePalabrasNoAlcanzadoException(Throwable cause) {
|
||||
super(cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public MinimoNumeroDePalabrasNoAlcanzadoException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public MinimoNumeroDePalabrasNoAlcanzadoException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public int getMinimoNumeroPalabras() {
|
||||
return minimoNumeroPalabras;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorFraseConPalabraBombilla;
|
||||
|
||||
public class PalabraBombillaNoEncontradaException extends Exception {
|
||||
|
||||
public PalabraBombillaNoEncontradaException() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraBombillaNoEncontradaException(String message) {
|
||||
super(message);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraBombillaNoEncontradaException(Throwable cause) {
|
||||
super(cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraBombillaNoEncontradaException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraBombillaNoEncontradaException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorFraseConPalabraBombilla;
|
||||
|
||||
public class PalabraOfensivaException extends Exception {
|
||||
|
||||
public PalabraOfensivaException() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraOfensivaException(String message) {
|
||||
super(message);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraOfensivaException(Throwable cause) {
|
||||
super(cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraOfensivaException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public PalabraOfensivaException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorFraseConPalabraBombilla;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Scanner;
|
||||
|
||||
import javax.swing.JOptionPane;
|
||||
|
||||
public class Principal {
|
||||
|
||||
|
||||
private static String getFraseConPalabraBombilla () throws SoloEspaciosEnBlancoException,
|
||||
MinimoNumeroDePalabrasNoAlcanzadoException,
|
||||
PalabraBombillaNoEncontradaException,
|
||||
PalabraOfensivaException {
|
||||
String frase = JOptionPane.showInputDialog("Introduzca una frase con la palabra \"bombilla\"");
|
||||
|
||||
// No frase formada por espacios en blanco
|
||||
if (frase.trim().equals("")) {
|
||||
throw new SoloEspaciosEnBlancoException("No hay palabras en la frase introducida");
|
||||
}
|
||||
// Mínimo número de palabras en 3.
|
||||
String palabras[] = frase.split("[ ]{1,}");
|
||||
if (palabras.length < 3) {
|
||||
throw new MinimoNumeroDePalabrasNoAlcanzadoException(3);
|
||||
}
|
||||
|
||||
// No aparece la palabra bombilla
|
||||
if (frase.toUpperCase().indexOf("BOMBILLA") == -1) {
|
||||
throw new PalabraBombillaNoEncontradaException();
|
||||
}
|
||||
|
||||
// Comprobar palabras ofensivas
|
||||
String palabrasOfensivas[] = new String[] {"tonto", "tonta", "idiota"};
|
||||
for (String palabraOfensiva : palabrasOfensivas) {
|
||||
if (frase.toLowerCase().indexOf(palabraOfensiva) != -1) {
|
||||
throw new PalabraOfensivaException("Palabra " + palabraOfensiva + " encontrada");
|
||||
}
|
||||
}
|
||||
|
||||
return frase;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
System.out.println(getFraseConPalabraBombilla());
|
||||
} catch (SoloEspaciosEnBlancoException e) {
|
||||
System.out.println(e.getMessage());
|
||||
} catch (MinimoNumeroDePalabrasNoAlcanzadoException e) {
|
||||
System.out.println("Tu frase debería ser más larga, al menos: " +
|
||||
e.getMinimoNumeroPalabras() + " palabras");
|
||||
} catch (PalabraBombillaNoEncontradaException e) {
|
||||
e.printStackTrace();
|
||||
} catch (PalabraOfensivaException e) {
|
||||
System.out.println(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorFraseConPalabraBombilla;
|
||||
|
||||
public class SoloEspaciosEnBlancoException extends Exception {
|
||||
|
||||
public SoloEspaciosEnBlancoException() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public SoloEspaciosEnBlancoException(String message) {
|
||||
super(message);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public SoloEspaciosEnBlancoException(Throwable cause) {
|
||||
super(cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public SoloEspaciosEnBlancoException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public SoloEspaciosEnBlancoException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorNumeroPar;
|
||||
|
||||
public class NumeroImparException extends Exception {
|
||||
|
||||
public NumeroImparException() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public NumeroImparException(String arg0) {
|
||||
super(arg0);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public NumeroImparException(Throwable arg0) {
|
||||
super(arg0);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public NumeroImparException(String arg0, Throwable arg1) {
|
||||
super(arg0, arg1);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
public NumeroImparException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
|
||||
super(arg0, arg1, arg2, arg3);
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque03_Excepciones.ExcepcionPorNumeroPar;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Principal {
|
||||
|
||||
private static int getNumeroPar () throws NumeroImparException {
|
||||
System.out.println("Introduzca número par: ");
|
||||
Scanner sc = new Scanner (System.in);
|
||||
int numero = sc.nextInt();
|
||||
|
||||
if (numero % 2 == 0) {
|
||||
return numero;
|
||||
}
|
||||
else {
|
||||
throw new NumeroImparException("El número: " + numero + " no es par");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
try {
|
||||
getNumeroPar();
|
||||
} catch (NumeroImparException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque04_Listener;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Principal {
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
int choice;
|
||||
|
||||
do {
|
||||
System.out.println("\nMenú de Operaciones Matemáticas:");
|
||||
System.out.println("1. Suma");
|
||||
System.out.println("2. Resta");
|
||||
System.out.println("3. Multiplicación");
|
||||
System.out.println("4. División");
|
||||
System.out.println("5. Raíz Cuadrada");
|
||||
System.out.println("6. Salir");
|
||||
System.out.print("Seleccione una opción: ");
|
||||
|
||||
choice = scanner.nextInt(); // Get user choice
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
// Suma
|
||||
System.out.print("Ingrese el primer número: ");
|
||||
int sum1 = scanner.nextInt();
|
||||
System.out.print("Ingrese el segundo número: ");
|
||||
int sum2 = scanner.nextInt();
|
||||
System.out.println("Resultado de la suma: " + (sum1 + sum2));
|
||||
break;
|
||||
|
||||
case 2:
|
||||
// Resta
|
||||
System.out.print("Ingrese el primer número: ");
|
||||
int sub1 = scanner.nextInt();
|
||||
System.out.print("Ingrese el segundo número: ");
|
||||
int sub2 = scanner.nextInt();
|
||||
System.out.println("Resultado de la resta: " + (sub1 - sub2));
|
||||
break;
|
||||
|
||||
case 3:
|
||||
// Multiplicación
|
||||
System.out.print("Ingrese el primer número: ");
|
||||
int mul1 = scanner.nextInt();
|
||||
System.out.print("Ingrese el segundo número: ");
|
||||
int mul2 = scanner.nextInt();
|
||||
System.out.println("Resultado de la multiplicación: " + (mul1 * mul2));
|
||||
break;
|
||||
|
||||
case 4:
|
||||
// División
|
||||
System.out.print("Ingrese el dividendo: ");
|
||||
int dividend = scanner.nextInt();
|
||||
System.out.print("Ingrese el divisor: ");
|
||||
int divisor = scanner.nextInt();
|
||||
|
||||
if (divisor != 0) {
|
||||
System.out.println("Resultado de la división: " + (dividend / divisor));
|
||||
}
|
||||
break;
|
||||
|
||||
case 5:
|
||||
// Raíz cuadrada
|
||||
System.out.print("Ingrese el número: ");
|
||||
int number = scanner.nextInt();
|
||||
|
||||
if (number >= 0) {
|
||||
System.out.println("Resultado de la raíz cuadrada: " + Math.sqrt(number));
|
||||
}
|
||||
break;
|
||||
|
||||
case 6:
|
||||
System.out.println("Saliendo del programa. ¡Adiós!");
|
||||
break;
|
||||
|
||||
default:
|
||||
System.out.println("Opción no válida. Intente de nuevo.");
|
||||
break;
|
||||
}
|
||||
|
||||
} while (choice != 6);
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private int menu() {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.println("\nMenú de Operaciones Matemáticas:");
|
||||
System.out.println("1. Suma");
|
||||
System.out.println("2. Resta");
|
||||
System.out.println("3. Multiplicación");
|
||||
System.out.println("4. División");
|
||||
System.out.println("5. Raíz Cuadrada");
|
||||
System.out.println("6. Salir");
|
||||
System.out.print("Seleccione una opción: ");
|
||||
|
||||
return scanner.nextInt();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque05_recursividad;
|
||||
|
||||
public class Ejercicio01_FibonacciRecursivo {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
int n = 7;
|
||||
System.out.println("El término " + n + " de la secuencia de Fibonacci es: " + fibonacci(n));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param n
|
||||
* @return
|
||||
*/
|
||||
public static int fibonacci(int n) {
|
||||
if (n <= 1) {
|
||||
return n; // Caso base: fibonacci(0) = 0 y fibonacci(1) = 1
|
||||
}
|
||||
return fibonacci(n - 1) + fibonacci(n - 2); // Llamadas recursivas
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque05_recursividad;
|
||||
|
||||
public class Ejercicio02_PotenciaRecursiva {
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param base
|
||||
* @param exponent
|
||||
* @return
|
||||
*/
|
||||
public static int potencia(int base, int exponente) {
|
||||
// Cualquier número elevado a 0 es 1
|
||||
if (exponente == 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return base * potencia(base, exponente - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
// Pruebas
|
||||
int base = 2;
|
||||
int exponent = 7;
|
||||
|
||||
System.out.println(base + " elevado a la " + exponent + " es: " + potencia(base, exponent));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package tutorialJava.capitulo7_Recursos.ejercicios.bloque05_recursividad;
|
||||
|
||||
public class Ejercicio03_ConteoRegresivo {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
int numero = 10;
|
||||
System.out.println("Conteo regresivo desde " + numero + ":");
|
||||
conteoRegresivo(numero);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param n
|
||||
*/
|
||||
public static void conteoRegresivo(int n) {
|
||||
if (n == 0) {
|
||||
return; // Cuando n llega a 0, termina la recursividad
|
||||
}
|
||||
System.out.println(n);
|
||||
conteoRegresivo(n - 1); // Llamada recursiva con n-1
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user