1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 1 Capítulo 5 Selección
2 Objetivos Implementar control por selección usando sentencias if Implementar control por selección usando sentencias switch Escribir expresiones booleanas usando expresiones relacionales y booleanas Evaluar correctamente expresiones booleanas Anidar una sentencia if dentro de otras sentencia Describir cómo se comparan los objetos Elegir la sentencia de control más apropiada para realizar una tarea
3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 3 La Sentencia if int testScore; testScore = //get test score input if (testScore < 70) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass" ); Esta sentencia se ejecuta si testScore es menor que 70. Esta sentencia se ejecuta si testScore es mayor que 70.
4 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 4 if ( testScore < 70 ) JOptionPane.showMessageDialog(null, "You did not pass" ); else JOptionPane.showMessageDialog(null, "You did pass " ); Sintáxis para la sentencia if if ( ) else Bloque Then Bloque Else Expresión booleana
5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 5 Control de flujo JOptionPane. showMessageDialog (null, "You did pass"); JOptionPane. showMessageDialog (null, "You did pass"); false testScore < 70 ? JOptionPane. showMessageDialog (null, "You did not pass"); JOptionPane. showMessageDialog (null, "You did not pass"); true
6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 6 testScore < 80 testScore * 2 >= 350 30 < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius =//mayor o igual a
7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 7 if (testScore < 70) { JOptionPane.showMessageDialog(null, "You did not pass“ ); JOptionPane.showMessageDialog(null, “Try harder next time“ ); } else { JOptionPane.showMessageDialog(null, “You did pass“ ); JOptionPane.showMessageDialog(null, “Keep up the good work“ ); } Sentencias Usar llaves si los bloques or tienen más de una sentencia, sino es opcional Bloque Then Bloque Else
8 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 8 if ( ) { … } else { … } Guia de Estilo if ( ) { … } else { … } Estilo 1 Estilo 2
9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 9 Sentencia if-then if ( ) if ( testScore >= 95 ) JOptionPane.showMessageDialog(null, "You are an honor student"); Bloque Then Expresión Booleana
10 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 10 Control de flujo de if-then testScore >= 95? false JOptionPane. showMessageDialog (null, "You are an honor student"); JOptionPane. showMessageDialog (null, "You are an honor student"); true
11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 11 Sentencias if anidadas Los bloques de then y else de una sentencia pueden contener cualquier sentencia válida, incluyendo otra sentencia if En ese caso recibe el nombre de anidada if (testScore >= 70) { if (studentAge < 10) { System.out.println(“Hiciste un buen trabajo"); } else { System.out.println(“Aprobaste"); //test score >= 70 } //and age >= 10 } else { //test score < 70 System.out.println(“No Aprobaste"); }
12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 12 Flujo de control de sentencias if anidadas messageBox.show ("You did not pass"); messageBox.show ("You did not pass"); false inner if messageBox.show ("You did pass"); messageBox.show ("You did pass"); false testScore >= 70 ? true studentAge < 10 ? messageBox.show ("You did a great job"); messageBox.show ("You did a great job"); true
13 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 13 Escribiendo un control if apropiado Fc. Cuántos de los 3 números son negativos if (num1 < 0) if (num2 < 0) if (num3 < 0) negativeCount = 3; else negativeCount = 2; else if (num3 < 0) negativeCount = 2; else negativeCount = 1; else if (num2 < 0) if (num3 < 0) negativeCount = 2; else negativeCount = 1; else if (num3 < 0) negativeCount = 1; else negativeCount = 0; if (num1 < 0) negativeCount++; if (num2 < 0) negativeCount++; if (num3 < 0) negativeCount++; La sentencia negativeCount++; incrementa la variable en uno La sentencia negativeCount++; incrementa la variable en uno
14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 14 Control if – else if Control if (score >= 90) System.out.print(“Puntaje A"); else if (score >= 80) System.out.print("Puntaje B"); else if (score >= 70) System.out.print("Puntaje C"); else if (score >= 60) System.out.print(" Puntaje D"); else System.out.print(" Puntaje F"); Test ScoreGrade 90 score A 80 score 90 B 70 score 80 C 60 score 70 D score 60 F
15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 15 El else se asocia a la sentencia If más cercana, usar {} en caso de duda if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); A A if (x < y) if (x < z) System.out.print("Hello"); else System.out.print("Good bye"); B B Are and different? A A B B if (x < y) { if (x < z) { System.out.print("Hello"); } else { System.out.print("Good bye"); } Both and means… A A B B
16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 16 Operadores Booleanos Un operaodor booleano toma valores booleanos si sus operandos devuelven un valor booleano Los 3 operadores son –Y :&&and –O :||or –No!not if (temperature >= 65 && distanceToDestination < 2) { System.out.println("Let's walk"); } else { System.out.println("Let's drive"); }
17 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 17 Semántica de Operadores Booleanos Operadores booleanos y significado PQP && QP || Q!P false true falsetruefalsetrue false truefalse true false
18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 18 Leyes de Morgan Las leyes de Morgan permiten escribir las expresiones booleanas de formas diferentes, permitiendo maneras más sencillas de interpretar Rule 1: !(P && Q) !P || !Q Rule 2: !(P || Q) !P && !Q !(temp >= 65 && dist < 2) !(temp >=65) || !(dist < 2) by Rule 1 (temp = 2)
19 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 19 Evaluación: circuito corto Consideremos las sig expresión booleana: x > y || x > z La expresión se evalúa de izq a derecha. Si x > y es verdadero, no es necesario evaluar x > z ya que la expresión entera será verdadera sea ya sea x > z verdadera o no Interrumpir la evaluación una vez que se puede determinar el resultado se llama evaluación de circuito corto Que ocurriría si no se realiza la evaluación por el circuito corto con la sig expresión? z == 0 || x / z > 20
20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 20 Reglas de precedencia vs usar ()
21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 21 Variables Booleanas El resultado de una expresión booleana es verdadero o falso (true false). Estos son los dos valores que puede tomar un dato de tipo boolean. Los booleanos ocupan 1 bit Podemos declarar una variable de tipo booleana y asignarle un valor boolean pass, done; pass = 70 < x; done = true; if (pass) { … } else { … }
22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 22 Métodos Booleanos Un método que devuelve un valor booleano: private boolean isValid(int value) { if (value < MAX_ALLOWED) return true; } else { return false; } Puede usarse como: if (isValid(30)) { … } else { … }
23 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 23 Comparando Objetos Para los datos primitivos sólo hay una manera de compararlos, los objetos (datos de tipo referencia) se pueden comparar de dos formas: 1.Verificar que las dos variables apunten al mismo objeto (usando ==) o 2.Verificar si ambos objetos tienen el mismo contenido
24 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 24 Usando== con objetos (ej 1) String str1 = new String("Java"); String str2 = new String("Java"); if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are not equal Son diferentes porque ambas variables apuntan a objetos != Puesto que el contenido de un dato de referencia es una dirección de mem
25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 25 Usando == con objetos (ej 2) String str1 = new String("Java"); String str2 = str1; if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are equal Es igual ambos apuntan al mismo objeto
26 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 26 Usando igual con String String str1 = new String("Java"); String str2 = new String("Java"); if (str1.equals(str2)) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are equal Son iguales pues tienen la misma secuencia de caracteres. La comparación de String es sensible a mayúscula minúscula (case sensitive)se puede usar el método equalsIgnoreCase
27 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 27 La semántica de ==
28 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 28 Creando Objetos String
29 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 29 La sentencia switch int gradeLevel; gradeLevel = JOptionPane.showInputDialog(“Nivel (Frosh-1,Soph-2,...):" ); switch (gradeLevel) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); break; case 3: System.out.print("Go to Harris Hall Rm A3"); break; case 4: System.out.print("Go to Bolt Hall Rm 101"); break; } Se ejecuta esta sentencia si gradeLevel es igual a 1 Se ejecuta esta sentencia si gradeLevel es igual a 4 La variable gradeLevel se llama variable de control puede se int o char
30 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 30 Sintáxis para la sentencia switch switch ( gradeLevel ) { case 1: System.out.print("Go to the Gymnasium"); break; case 2: System.out.print("Go to the Science Auditorium"); break; case 3: System.out.print("Go to Harris Hall Rm A3"); break; case 4: System.out.print("Go to Bolt Hall Rm 101"); break; } switch ( ) { : … : } Case Body Expresión Aritmética Case Label
31 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 31 switch sin sentecias break switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; } x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? false true
32 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 32 switch con sentencias break switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; } x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? false true break;
33 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 33 Switch con el Bloque por defecto switch (ranking) { case 10: case 9: case 8: System.out.print("Master"); break; case 7: case 6: System.out.print("Journeyman"); break; case 5: case 4: System.out.print("Apprentice"); break; default: System.out.print("Input error: Invalid Data"); break; }
34 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 34 Dibujando Gráficos Clases estándard relacionadas con el dibujo de formas geométricas. –java.awt.Graphics –java.awt.Color –java.awt.Point –java.awt.Dimension Revisar Java API para más detalles
35 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 35 Ej Dibujo de un rectángulo
36 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 36 El efecto de drawRect
37 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 37 Definición del Problema Problem statement: Escribir una aplicación que simule un protector de pantalla dibujando varias formas geométricas de diferentes formas y colores. El usuario tiene la opción de elegir el tipo de figura (elipse o rectángulo), color y movimiento ( estacionario, aleatorio, inmóvil)
38 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 38 Plan General Tareas: –Obtener la forma que el usuario desea –Obtener el color –Obtener el tipo de movimiento –Comenzar el dibujo
39 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 39 Clases Requiridas Ch5DrawShapeDrawingBoardJOptionPaneDrawableShape class we implement helper class given to us standard class
40 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 40 Desarrollo Desarrollaremos esto en 6 pasos: 1.Comenzamos con una plantilla del programa.Vemos la clase DrawingBoard 2.Definir una clase DrawableShape experimental que dibuje una forma ficticia 3.Agregar código para permitirle al usuario elegir una forma. Extender la clase DrawableShape y las otras en caso necesario 4.Agregar código que le permita al usuario especificar un color. Add code to allow the user to specify the color. Extender la clase DrawableShape y las otras en caso necesario 5.Agregar código que le permita al usuario especificar el tipo de movimiento deseado. Extender la clase DrawableShape y las otras en caso necesario 6.Finalizar programa
41 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 41 Paso 1 Diseño Los métodos de la clase DrawingBoard –public void addShape(DrawableShape shape) Agrega una forma a DrawingBoard.No hay un límite de la cantidad de formas que se pueden agregar public void setBackground(java.awt.Color color) Pone el color de fondo de la ventana al color elegido public void setDelayTime(double delay) Pone el tiempo de retardo (delay) entre dibujos en seg public void setMovement(int type) Pone el tipo de movimiento a STATIONARY, RANDOM, or SMOOTH public void setVisible(boolean state) Pone la ventana a visible public void start( ) Comienza a dibujar y agregar formas usando el tipo de movimiento elegido y el retardo
42 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 42 Paso 1 Código Directory: Chapter5/Step1 Source Files: Ch5DrawShape.java Directory: Chapter5/Step1 Source Files: Ch5DrawShape.java
43 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 43 Paso 1 Test Corremos el programa para verificar que una ventana DrawingBoard con fondo negro se muestre toda la pantalla
44 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 44 Paso 2 Diseño Definir una clase DrawableShape preliminar Los métodos necesarios para esta son: –public void draw(java.awt.Graphics g) Dibuja una forma del objeto g. –public java.awt.Point getCenterPoint( ) Retorna el punto central de esta forma –public java.awt.Dimension getDimension( ) Retorna los límites rectangulares de esta forma –public void setCenterPoint(java.awt.Point pt) Coloca el punto central de la forma a pt.
45 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 45 Paso 2 Código Directory: Chapter5/Step2 Source Files: Ch5DrawShape.java DrawableShape.java Directory: Chapter5/Step2 Source Files: Ch5DrawShape.java DrawableShape.java
46 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 46 Paso 2 Test Compilar y correr el programa varias veces Confirmar los tipos de movimiento STATIONARY, RANDOM, and SMOOTH. Probar con distintos tiempos de retardo Experimentar con diferentes colores de fondo
47 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 47 Paso 3 Diseño Extendemos la clase main para permitirle al usuario elegir una forma Daremos tres opciones de forma: elipse, rectángulo y rectángulo redondeado Tambien necesitamos rutinas para que el usuario ingrese la informacion de tamaño y punto central. El punto central determina donde se va a dibujar la forma sobre DrawingBoard. Los 3 métodos para ingresar la información son: private int inputShapeType( ) private Dimension inputDimension( ) private Point inputCenterPoint( )
48 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 48 Paso 3 Código Directory: Chapter5/Step3 Source Files: Ch5DrawShape.java DrawableShape.java Directory: Chapter5/Step3 Source Files: Ch5DrawShape.java DrawableShape.java
49 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 49 Paso 3 Test Correr e programa con diferentes valores de ingreso y comprobar los resultados Intentar ingresos válidos e inválidos y confirmar que la respuesta sea la aporpiada
50 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 50 Paso 4 Diseño Extender la clase main para permitirle al usuario elegir un color Le permitiremos al usuario elegir uno de los 5 colores EL método de ingreso de color es: private Color inputColor( )
51 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 51 Paso 4 Código Directory: Chapter5/Step4 Source Files: Ch5DrawShape.java DrawableShape.java Directory: Chapter5/Step4 Source Files: Ch5DrawShape.java DrawableShape.java
52 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 52 Paso 4 Test Correr el programa con distintos colores Probar con ingresos válidos e inválidos
53 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 53 Paso 5 Diseño Extender la clase main para permitirle al usuario elegir el tipo de movimiento Permitiremos uno de los 3 posibles movimientos El método para ingresar el movimiento es: private int inputMotionType( )
54 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 54 Paso 5 Código Directory: Chapter5/Step5 Source Files: Ch5DrawShape.java DrawableShape.java Directory: Chapter5/Step5 Source Files: Ch5DrawShape.java DrawableShape.java
55 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 55 Paso 5 Test Correr el programa varias veces con distinto tipo de movimiento. Intentar con ingresos válidos e inválidos
56 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 5 - 56 Paso 6: Finalizar Posible Extensiones –Transformar la forma del objeto –Cambiar el color del objet –Dibujar multiples objetos –Dibujar texto que se desplace