Condicionales

Profesor: Santiago Quiñones

Lenguaje de Programación - Informática

https://bit.ly/condicionales-java

Contenidos

Estructuras selectivas anidadas

if anidado 

if (expresion_logica_A){
  instrucciones 1
}else{
  if (expresion_logica_B){
    instrucciones 2
  }else{
    instrucciones 3
  }
}
instrucción siguiente
# PRESENTING CODE

El if anidado en java se forma por lo general usando if-else. El formato es:

Este es el if anidado

Usando if/else anidados (condición múltiple)

boolean llueve = true;
float temperatura = sc.nextFloat();

if (temperatura < 18){
    if (llueve == true){
        System.out.println('Llevaré paraguas y abrigo');
    }
    else{
        System.out.println('Solo llevaré abrigo')
    }
}else{
    System.out.println('No necesito paraguas ni abrigo')
}
# PRESENTING CODE

if anidado en java

if (expresion_logica_A){
  instrucciones 1
}elif (expresion_logica_B){
    instrucciones 2
}else{
    instrucciones 3
}  
    
instrucción siguiente
# PRESENTING CODE

Una manera más común de escribir el if anidado es por medio de la contracción de else-if que es elif. Después de un elif debemos añadir una condición. El formato es el siguiente:

if (expresion_logica_A){
  instrucciones 1
}else{
  if (expresion_logica_B){
    instrucciones 2
  }else{
    instrucciones 3
  }
}
 instrucción siguiente
# Lo siguiente también implica decisiones basadas 
# en la edad de una persona:


int edad = scanner.nextInt();

if (edad < 13) {
  System.out.println("Eres un niño.");
} else if (edad >= 13 && edad < 20) {
  System.out.println("Eres un adolescente.");
} else if (edad >= 20 && edad < 30) {
  System.out.println("Tienes veinte años.");
} else if (edad >= 30 && edad < 40) {
  System.out.println("Tienes más de 30 años.");
} else if edad >= 40{
  System.out.println("Es usted un sobreviviente.");
}
# PRESENTING CODE

Evite el código demasiado complicado

# Lo siguiente también implica decisiones basadas 
# en la edad de una persona:


int edad = scanner.nextInt();

if (edad < 13) {
  System.out.println("Eres un niño.");
} else if (edad < 20) {
  System.out.println("Eres un adolescente.");
} else if (edad < 30) {
  System.out.println("Tienes veinte años.");
} else if (edad < 40) {
  System.out.println("Tienes más de 30 años.");
} else {
  System.out.println("Es usted un sobreviviente.");
}
# PRESENTING CODE

Evite el código demasiado complicado

Se omite escribir edad >= 13, debe tener la seguridad que en este caso no llegan los valores menores a 30. Lo mismo sucede con el resto de casos

Reto 1:

# PRESENTING CODE

El valor de y se define como sigue:

y = x^2 + 2x - 3 \quad si \quad -3\leq x \leq 2\\ y = 5x + 7 \quad si \quad 2 < x \leq 10\\ y = 0 \quad si \quad x < -3 \quad ó \quad x > 10
public class EstructurasSelectivasEcuaciones {
    public static void main(String[] args) {
        double x = 10;
        double y;
        
        if (x >= -3 && x <= 2){
            y = Math.pow(x, 2) + 2*x - 3;
        }else if(x > 2 && x <= 10){
            y = 5*x + 7;
        }else{
            y = 0;
        }
        
        System.out.printf("x: %f, y: %f", x, y);
        
 
    }
}

Solución: 

Escriba un programa que lea el valor de x y

determine el valor de y.

switch

switch

int valor = 2; // Ejemplo de valor a evaluar

switch (valor) {
    case valor1:
        // Código a ejecutar si valor es igual a valor1
        break;
    case valor2:
        // Código a ejecutar si valor es igual a valor2
        break;
    // ... otros casos
    default:
        // Código a ejecutar si ninguno de los casos anteriores coincide con el valor
}
# PRESENTING CODE

La estructura switch es similar al if-else if-else pero escrito de una manera más compacta. El formato es:

Ejemplo 1

Ejemplo 2

Reto 2:

# PRESENTING CODE

Crear un menú de platos de comida para merendar.

// Objeto para leer desde teclado
Scanner sc = new Scanner(System.in);

System.out.println("Seleccione que quiere merendar");
System.out.println("[1] Chaulafan");
System.out.println("[2] Repe");
System.out.println("[3] Tallarines");

System.out.print("Ingrese su opción: ");
int opcion = sc.nextInt();

if (opcion == 1){
  System.out.println("Comiendo un chaulafan..");
}else if (opcion == 2){
  System.out.println("Comiendo un repe");
}else if (opcion == 3){
  System.out.println("Comiendo tallarines");
}else{
  System.out.println("Opción incorrecta");
}

Solución: 

Reto 2:

# PRESENTING CODE

Resuelto con la estructura switch

// Objeto para leer desde teclado
Scanner sc = new Scanner(System.in);

System.out.println("Seleccione que quiere merendar");
System.out.println("[1] Chaulafan");
System.out.println("[2] Repe");
System.out.println("[3] Tallarines");

System.out.print("Ingrese su opción: ");
int opcion = sc.nextInt();

switch (opcion) {
  case 1:
    System.out.println("Comiendo un chaulafan..");
    break;
  case 2:
    System.out.println("Comiendo un repe");
    break;
  case 3:
    System.out.println("Comiendo tallarines");
    break;
  default:
    System.out.println("Opción incorrecta");
}

Solución: 

Taller - Problema 1: Solución

# PRESENTING CODE
// Creación de objetos
Scanner sc = new Scanner(System.in);

// Definición de constantes
        
// Definición de variables
float montoFactura;
float costoProducto1;
int cantidadProducto1;
float costoProducto2;
int cantidadProducto2;

float gastoTransporte;

float subtotal;

float impuesto;
float porcentajeDescuento;
float descuento;

// Ingreso de datos
System.out.println("Producto 1: ");
System.out.print("Cantidad: ");
cantidadProducto1 = sc.nextInt();
System.out.print("Costo: ");
costoProducto1 = sc.nextFloat();


System.out.println("Producto 2: ");
System.out.print("Cantidad: ");
cantidadProducto2 = sc.nextInt();
System.out.print("Costo del segundo producto: ");
costoProducto2 = sc.nextFloat();

System.out.print("Gasto de envio: ");
gastoTransporte = sc.nextFloat();

subtotal = (cantidadProducto1 * costoProducto1) + (cantidadProducto2 * costoProducto2);
System.out.printf("Subtotal: %f \n", subtotal);

impuesto = subtotal * IVA;
System.out.printf("IVA: %f \n", impuesto);

subtotal = subtotal + impuesto;
System.out.printf("SubTotal + IVA: %f \n", subtotal);

if (subtotal > 1000){
  porcentajeDescuento = 0.2f;
}else{
  porcentajeDescuento = 0.05f;
}

descuento = subtotal * porcentajeDescuento;
System.out.printf("Descuento: %f \n", descuento);

subtotal = subtotal - descuento;

if (subtotal > 5000 ){
  gastoTransporte = 0f;
}

System.out.printf("Gasto de envío: %f \n", gastoTransporte);


montoFactura = subtotal + gastoTransporte;

System.out.printf("Monto Factura: %f", montoFactura);

Es recomendable intente resolver el problema de forma individual, si existe alguna duda utilice esta referencia. 

Condicionales #Computación

By lsantiago

Condicionales #Computación

  • 65