CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2013
Chapter 3 Presentation Outline The if Statement The if - else Statement Nested if statements The if - else - if Statement Logical Operators Comparing String Objects The Conditional operator The Switch Operator Formatting the output.
The IF statement I need to go to the lab! If it’s cold outside, I’ll wear a coat Condition (true or false) The “action” if the “condition” is true
The if Statement How do we code this situation in Java (and other languages): if (condition is true) execute next statement 3-6 What things could provide “true” or “false” values?
Boolean Expressions A boolean expression is any variable or calculation that results in a true or false condition. 3-7 ExpressionMeaning x > y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x <= y Is x less than or equal to y. x == y Is x equal to y? x != y Is x not equal to y?
if Statements and Boolean Expressions double x = 10, y = 5, z = 10; if (x > y) System.out.println("X is greater than Y"); if(x == z) System.out.println("X is equal to Y"); if(x != y) { System.out.println("X is not equal to Y"); x = y; System.out.println("However, now it is."); } Example: slides from Editor\Chapter 03\AverageScore.javaslides from Editor\Chapter 03\AverageScore.java 3-8
Flowcharts IF statements can be modeled as a flow chart. 3-9 Wear a coat. Yes Is it cold outside? No System.out.println(“1”); if (coldOutside) wearCoat(); System.out.println(“2”);
Flowcharts A block if statement may be modeled as: 3-10 Wear a coat. Yes Is it cold outside? Wear a hat. Wear gloves. if (coldOutside) { wearCoat(); wearHat(); wearGloves(); } Note the use of curly braces to block several statements together.
if - else Statements The if - else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementOrBlockIfTrue; else statementOrBlockIfFalse; See example: slides from Editor\Chapter 03\Division.javaslides from Editor\Chapter 03\Division.java 3-12
if - else Statement Flowcharts 3-13 Wear a coat. Yes Is it cold outside? Wear shorts. No
Nested if Statement Flowcharts 3-15 Wear a jacket. Yes Is it cold outside? Wear shorts. Is it snowing? Wear a parka. No Yes
Nested if Statements 3-16 if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); }
if - else - if Statements 3-18 if (expression_1) { statement; etc. } else if (expression_2) { statement; etc. } Insert as many else if clauses as necessary else { statement; etc. } If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. These statements are executed if none of the expressions above are true.
if - else - if Statements See example: slides from Editor\Chapter 03\TestResults.javaslides from Editor\Chapter 03\TestResults.java 3-19
if - else - if Flowchart 3-20
if (score < 60) { grade = “F”; } else if (score < 70) { grade = “D”; } else if (score < 80) { grade = “C”; } else if (score < 90) { grade = “B”; } else if (score <= 100) { grade = “A”; } else { grade = “X”; } if (score < 60) { grade = “F”; } if (score < 70) { grade = “D”; } if (score < 80) { grade = “C”; } if (score < 90) { grade = “B”; } if (score <= 100) { grade = “A”; } else { grade = “X”; } Do They produce the same results? Is there any advantage in using else-if instead of just IFs?
AND The AND Operator
In what pair of conditions will Jenny will go to NY? 3-24 got paid Megabus ticket is still available Is Jenny going to NY? truefalse truefalse true See LogicalAnd.java programprogram
OR
The OR Operator 3-26 Suzan is going with Jenny Megabus ticket is still available Is Jenny going to NY? truefalsetrue falsetrue false true See LogicalOr.java programprogram
The NOT Operator 3-27 gotSick!gotSick truefalse true
Logical Operators 3-28 OperatorMeaningExample && AND if (ticketIsAvailable && gotPaid) || OR if (SuzanIsGoing || ticketIsAvailable) ! NOT if (!gotSick)
Other ways of getting boolean values Boolean Expressions x==y (returns true or false) x<y Methods can return true and false isColdOutside() (returns true or false) We can use this return inside the IF statement if (isColdOutside()) { wearCoat(); }
Comparing String Objects A method from the String Class: public boolean equalsIgnoreCase(String anotherString) 3-32
A method from the String Class: public boolean equalsIgnoreCase(String anotherString) String name = “John”; if (name.equalsIgnoreCase(“Paulo”)) { System.out.println(“They have the same name”); } else { System.out.println(“They have different names”); }
Ignoring Case in String Comparisons See examples slides from Editor\Chapter 03\StringCompare.java slides from Editor\Chapter 03\StringCompareTo.java slides from Editor\Chapter 03\StringCompareTo.java SecretWord.java 3-34
The switch Statement switch(Expression) { case CaseExpression: // place one or more statements here break; case CaseExpression: // place one or more statements here break; // case statements may be repeated //as many times as necessary default: // place one or more statements here } 3-36
The case Statement The break statement ends the case statement. The break statement is optional. If a case does not contain a break, then program execution continues into the next case. See example: NoBreaks.javaNoBreaks.java See example: PetFood.javaPetFood.java The default section is optional and will be executed if no CaseExpression matches the SwitchExpression. See example: slides from Editor\Chapter 03\SwitchDemo.javaslides from Editor\Chapter 03\SwitchDemo.java 3-37
(Self study if time does not permit)
The printf Method 3-39 double grossPay = ; System.out.println("Your pay is “ + grossPay);
The printf Method 3-40 System.out.printf(FormatString, ArgList); FormatString is a string that contains text and/or special formatting specifiers. ArgList is optional. It is a list of additional arguments that will be formatted according to the format specifiers listed in the format string.
The printf Method 3-41 double grossPay = ; System.out.printf("Your pay is %f.\n", grossPay); The %f format specifier indicates that a floating-point value will be printed. The contents of the grossPay variable will be printed in the location of the %f format specifier.
The printf Method 3-42 double grossPay = ; System.out.printf("Your pay is %.2f.\n", grossPay); The %.2f format specifier indicates that a floating-point value will be printed, rounded to two decimal places.
The printf Method 3-43 int hours = 40; System.out.printf("I worked %d hours.\n", hours); The %d format specifier indicates that a decimal integer will be printed. The contents of the hours variable will be printed in the location of the %d format specifier.
The printf Method 3-44 int dogs = 2, cats = 4; System.out.printf("We have %d dogs and %d cats.\n", dogs, cats);
The printf Method 3-45 String name = "Ringo"; System.out.printf("Your name is %s.\n", name); The %s format specifier indicates that a string will be printed.
Other way of decimal formatting import java.text.DecimalFormat; DecimalFormat df = new DecimalFormat("####0.00"); String formattedNumber = df.format(doubleNumber); Example: double doubleNumber = 15.0/3.14; ( ) String formattedNumber = df(doubleNumber); (4.77) Note: formattedNumber is a String!!! Good to be used on System.out.println or in a text field in a dialog box.
Any Questions? 48
Homework / lab