Download presentation
Presentation is loading. Please wait.
1
CS0007: Introduction to Computer Programming
Decision Structures: The If-Else If Statement, Nested If Statements, Logical Operators, and String Comparison CS0007: Introduction to Computer Programming
2
Review In a decision structure’s simplest form certain statements are executed only when… a specific condition exists. It is said that the statements inside of the decision structure are… conditionally executed. Relational Operators determine whether… a specific relationship exist between two values. Some relational operators in Java are… > , < , >= , <= , == , !=
3
Review if(BooleanExpression) statement; if(BooleanExpression) {
General form of an if statement: if(BooleanExpression) statement; if(BooleanExpression) { statement1; statement2; ... } A Flag is… a boolean variable that signals when some condition exists in a program. When Java compares characters, it compares the character’s… Unicode values
4
Review General form of an if-else statement: if(BooleanExpression)
statement or block 1 else statement or block 2
5
The if-else if Statement
Sometimes you need to be able to test a series of conditions You can do this with the if-else if statement General form: if (BooleanExpression1) statement or block 1 else if(BooleanExpression2) statement or block 2 else statement or block 3 If BooleanExpression1 is true, then statement or block 1 is executed. If BooleanExpression1 is false, then BooleanExpression2 is tested. If BooleanExpression2 is true, then statement or block 2 is executed. If BooleanExpression2 is false, then statement or block 3 is executed. Note: You can have as many if else clauses as is needed.
6
if-else if Example import java.util.Scanner; public class IfElseIfStatement { public static void main(String[] args) { int testScore; Scanner keyboard = new Scanner(System.in); System.out.print("Enter your numeric test score: "); testScore = keyboard.nextInt(); if (testScore < 60) System.out.println("Your grade is an F."); else if (testScore < 70) System.out.println("Your grade is a D."); else if (testScore < 80) System.out.println("Your grade is a C."); else if (testScore < 90) System.out.println("Your grade is a B."); else if (testScore < 101) System.out.println("Your grade is an A."); else System.out.println("Invalid Grade"); }
7
Nested if Statements Nesting is enclosing one structure inside of another. A block in Java can contain any valid Java code, this includes other if statements: if(BooleanExpression1) { if(BooleanExpression2) { statement1; statement2; } statement3; statement4; If BooleanExpression1 is true and BooleanExpression2 is true , what is executed? statement1 , statement2 , statement3 , statement4 If BooleanExpression1 is true and BooleanExpression2 is false , what is executed? statement3 , statement4 If BooleanExpression1 is false, what is executed? Nothing
8
Nested if Statements Example
import java.util.Scanner; public class NestedIfStatements { public static void main(String[] args) { double salary, yearsOnJob; Scanner keyboard = new Scanner(System.in); System.out.print("Enter your annual salary: "); salary = keyboard.nextDouble(); System.out.print("Enter the number of years at your current job: "); yearsOnJob = keyboard.nextDouble(); if (salary >= 30000) { if (yearsOnJob >= 2) System.out.println("You qualify for a loan."); else System.out.println("You must have been at your current job " + "for at least 2 years to qualify."); } else { System.out.println("You must earn at least $30,000 per year " + "to qualify."); }
9
Logical Operators Java provides logical operators.
The binary logical operators combine two boolean expressions into one. The unary logical operator switches the value of a boolean expression. Binary logical operators have lower precedence than relational operators (they will be evaluated after) NOT has the same precedence as negation. Operator Meaning Kind && AND Binary || OR ! NOT Unary
10
Logical Operator Truth Tables
Truth Tables show the result of a logical expression based on the values of the operands. Op1 Op2 Op1 && Op2 true false Op1 Op2 Op1 || Op2 true false Op1 !Op1 true false
11
Logical Operator Practice
2 > 3 && 4 < 5 false – first operand is false 2 < 3 && 4 < 5 true 2 > 3 || 4 < 5 2 > 3 || 4 > 5 false – both operands are false !(2 > 3) true – operand is false
12
Logical AND Example import java.util.Scanner; public class LogicalAndOperator { public static void main(String[] args) { char walks, quacks; Scanner keyboard = new Scanner(System.in); System.out.print("Does it walk like a duck (Y or N)? "); walks = keyboard.nextLine().charAt(0); System.out.print("Does it quack like a duck (Y or N)? "); quacks = keyboard.nextLine().charAt(0); if(walks == 'Y' && quacks == 'Y') System.out.println("It's proabably a duck."); else System.out.println("It's proabably NOT a duck."); } }
13
Logical AND and Nesting
If we have the && operator, do we need nesting? if(BooleanExpression1) { if(BooleanExpression2) { Both conditions met } else { Both conditions NOT met if(BooleanExpression1 && BooleanExpression2) {
14
Logical AND and Nesting
Answer: Yes, to act if one of the conditions is not met: if(BooleanExpression1) { if(BooleanExpression2) { Both conditions met } else { Condition 2 not met Condition 1 not met if(BooleanExpression1 && BooleanExpression2) { Both conditions NOT met
15
*Copy of program in separate packet
Exercise Change NestedIfStatement.java to tell the user if she does not meet one requirement, the other requirement, or BOTH. Hint: we talked about something last lecture that will help us… Flags *Copy of program in separate packet
16
Logical OR Example import java.util.Scanner; public class LogicalOrOperator { public static void main(String[] args) { char raining, bothTeamsPresent; Scanner keyboard = new Scanner(System.in); System.out.print("Is it raining (Y or N)? "); raining = keyboard.nextLine().charAt(0); System.out.print("Are both teams present (Y or N)? "); bothTeamsPresent = keyboard.nextLine().charAt(0); if(raining == 'Y' || bothTeamsPresent == 'N') System.out.println("We can't play..."); else System.out.println("Play ball!"); } }
17
*Copy of program in separate packet
Exercise Change LogicalOrOperator.java to allow the user to enter capital or lower case Y or N as an answer. Hint Use another OR operator. Also, check to make sure the user entered a valid response. Y, N, y, or n. *Copy of program in separate packet
18
Comparing String Objects
Imagine you have declared two String variables as such: String x = "buffalo"; String y = “bison"; What does x == y resolve to? false, but not for the reason you think! The == operator compares what the reference values are (what objects they are pointing to), NOT what the value of the string is. In some cases this causes problems You should use methods in the String class in order to compare String variables equals compareTo
19
String equals method To check if two strings are the same you can use the equals method. StringReference.equals(OtherString); If the string referred to by StringReference is equal to the one referred to by OtherString, then true is returned. Otherwise false is returned. This comparison is case-sensitive ("buffalo" and "Buffalo" are not equal) To do case-insensitive comparison, use equalsIgnoreCase
20
String compareTo method
If you want to determine which string is “greater” use the compareTo method. StringReference.compareTo(OtherString); If the string referred to by StringReference is equal to the one referred to by OtherString, then 0 is returned. If the string referred to by StringReference is “less than” to the one referred to by OtherString, then a negative number is is returned. If the string referred to by StringReference is “greater than” to the one referred to by OtherString , then a positive number is returned. This comparison is case-sensitive ("buffalo" and "Buffalo" are not equal) To do case-insensitive comparison, use compareToIgnoreCase
21
String compareTo method
What does it mean for strings to be “greater than” or “less than” each other? Java compares the two strings, character by character from left to right. When there is a difference in a character it compares the Unicode values of the characters. If a string is shorter than another, and the shorter one is the beginning of the longer one, the shorter one is considered less. "hi" is less than "high"
22
String Comparison Example
*Copy of program in separate packet
23
Block-Level Scope If a variable is declared inside of a block, it is said to have block-level scope. If a variable has Block-Level Scope it is in scope from its declaration to the ending of the block in which it was declared. if(BooleanExpression) { int x; … } The variable x has scope from the point it was declared to the } This does not have much use now, but will be more useful when we learn loops.
24
The Conditional Operator
Java provides and operator to create short expressions that work like if-else statements. BooleanExpression ? Value1 : Value2; If BooleanExpression is true, Value1 is returned If BooleanExpression is false, Value2 is returned Example: if (score < 60) System.out.println("You Fail"); else System.out.println("You Pass"); System.out.println("You " + score < 60 ? "Fail" : "Pass");
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.