Sie sind auf Seite 1von 3

Clase 3: Instrucción if-else

Problema Solución 3 (más natural)


Escribir un método (función) que reciba dos enteros y entregue el
mayor de los dos (sin usar Math.max). Ej: int m = mayor(a,b); static public int mayor(int x, int y)
{
min(x,y) if( x > y )
Solución return x;
|x-y|
else
static public int mayor(int x, int y){ return y;
return Math.min(x,y) + Math.abs(x-y); }
}
(x+y)/2
¿Significado?
Solución 2
|x-y|
si x es mayor que y,
static public int mayor(int x, int y){
return (x + y + Math.abs(x-y))/2; entonces entregar el valor de x,
} si no, es decir si x es menor o igual que y, devolver el valor de y

Instrucción if-else Instrucción if-else

Sintaxis Semántica

if( condición ) • Si condición se cumple (es verdadera), ejecutar instrucción1


instrucción1;
else • Si condición no se cumple (es falsa), ejecutar instrucción2
instrucción2;
• Gráficamente:
verdadera condición falsa

instrucción1 instrucción2

Condición (condición simple o comparación) Caso especial 1: cada instrucción puede ser otro if-else
static public int mayor(int x,int y,int z)
sintaxis: expresión1 operador-de-relación expresión2 {
operador de relación (comparación): <,>,<=,>=,==,!= if( x >= y )

semántica: if( x >= z )


• evaluar expresiones return x;
• comparar resultados de expresiones else
• si condición se cumple entregar valor verdadero (true) return z;
• si condición no se cumple entregar valor falso (false)
else
ejemplo
if( b*b >= 4*a*c ) if( y >= z )
U.println(“raices reales”); return y;
else else
U.println(“raices complejas”); return z;
}

18-03 (B. Bustos) 1


Clase 3: Instrucción if-else

Caso especial 2: else puede omitirse Caso especial 3:


bloque {...} para agrupar varias instrucciones
static public int mayor(int x,int y,int z) …
{ if( a>=b)
int aux=x; {
mayor=a;
if( y > aux) aux=y; menor=b;
}
if( z > aux) aux=z; else
{
return aux; mayor=b;
} menor=a;
}

Condiciones compuestas Con indentación (uso de márgenes) que evidencia selección múltiple:
static public int mayor(int x,int y,int z)
static public int mayor(int x,int y,int z)
{
{
if( x >= y && x >= z )
if( x >= y && x >= z )
return x;
return x;
else
else if( y >= z )
if( y >= z )
return y;
return y;
else
else
return z;
return z;
}
}
if(cond1)
inst1
else if(cond2)
inst2

else
inst

Condición compuesta
sintaxis prioridades de operadores
• condición1 operador-lógico condición2 . . . (orden de evaluación)
• operador lógico:
1 + - ! (unarios)
&&: y, and, conjunción
2 (tipo) coerción
||: o, or, disyunción
3 * / %
!: no, not, negación (operador unario) 4 + -
semántica 5 < > <= >=
c1 c2 c1 && c2 c1 || c2 !c1 6 == !=
V V V V F 7 &&
V F F V F 8 ||
F V F V V
F F F F V
V si ambos V V si alguno V V si F
Nota. c2 se evalúa sólo si es necesario. Por ej
if(x>=y && x>=z)... si x<y entonces x>=z no se evalúa

18-03 (B. Bustos) 2


Clase 3: Instrucción if-else

Problema. Escribir los métodos iguales y main int iguales(double x,double y,double z){
class Programa{
//iguales(x,y,z): cantidad de números iguales (3,2, o 0) if(x==y && x==z)
//ej:iguales(1,2,3)=0,iguales(1,2,1)=2,iguales(1,1,1)=3 return 3;
static public int iguales(double x,double y,double z){
… else if(x==y || x==z || y==z)
}
static public void main(String[]arg)throws IOException{ return 2;

}
else
} return 0;
Diálogo del programa principal:
Tipo de triángulo de lados a,b,c
}
a? __
b? __
c? __
equilátero,isósceles,o,escaleno

Solución 2. Con if sin else U.println(“Tipo de triángulo de lados a,b,c");


int iguales(double x,double y,double z){ double
if(x==y && x==z) return 3; a=U.readDouble(“a?”),
if(x==y || x==z || y==z) return 2; b=U.readDouble(“b?”),
return 0; c=U.readDouble(“c?”);
} int n=iguales(a,b,c);
Solución 3. “negando” la 2ª condición if( n == 3 )
int iguales(double x,double y,double z){ U.println(“equilátero");
if(x==y && x==z) return 3; else if( n == 2 )
if(x!=y && x!=z && y!=z) return 0; U.println(“isósceles");
return 2; else
} U.println(“escaleno");

Tipo boolean Funciones


ejemplo:
constantes: true (verdadero) y false (falso) static public boolean par(int x){
return x%2==0;
variables: boolean nombre; }
equivalencia:
expresiones: condiciones static public boolean par(int x){
if(x%2==0) return true; else return false;
asignación: variable=condición; }
uso
if(par(n))… ;else …;
ejemplos:
boolean p ;
sintaxis
p = a>=b && a>=c;
static public boolean nombre(parámetros){
if( p ) //equivalencia: if( p==true ) instrucciones;
U.println(“mayor=”+a); return condición (exp de tipo boolean);
}

18-03 (B. Bustos) 3

Das könnte Ihnen auch gefallen