Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
27 views28 pages

INFO6066 - Selection (Decision) Control Structures

The document discusses control structures in procedural programming like if-else and switch case statements. It provides examples of using relational and logical operators in if/else-if conditional statements for tasks like grade calculation. The use of logical AND and OR operators to check multiple conditions at once is also explained.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views28 pages

INFO6066 - Selection (Decision) Control Structures

The document discusses control structures in procedural programming like if-else and switch case statements. It provides examples of using relational and logical operators in if/else-if conditional statements for tasks like grade calculation. The use of logical AND and OR operators to check multiple conditions at once is also explained.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Software and Information Systems Testing

INFO 6066 Coding for Test

If-else and switch case structures

1 INFO6066
Software and Information Systems Testing

Recap: The Three Control Structures in Procedural Programming…

• Recap: software crisis of the late 60’s…caused primarily by


“spaghetti code” written using the GOTO statement.
• Bohm and Jacopini paper proved that GOTO was not needed
and that all programs could be written using the three primary
control structures of:
– Sequence (lines of code execute in sequential order)
– Selection (conditional structures such as ‘if-then-else’)
– Repetition (loop structures)
• SSR!

2 INFO6066
Software and Information Systems Testing

Relational Operators
• Used when doing comparisons such as greater than or less than between
data values in Boolean (TRUE or FALSE) expressions
• == means “is equal to”
• > means greater than
• >= means greater than or equal to
• < means less than
• <= means less than or equal to
• These operators are usually found in loops and conditional (branching)
statements like an “if” statement.
if (yourAge > 50)
{
System.out.println("Yep! You’re old!");
}

3 INFO6066
Software and Information Systems Testing

if Statements in Java
• An if structure is a single-selection type of structure because it either
selects to carry out, or it ignores, a single action.

• if ( some boolean expression)


{
block statement to be executed if expression is true;
}
next line of code;

• If the boolean expression evaluates to TRUE, then block statement is


executed.
• IF boolean expression is FALSE, it ignores the block statement and
executes the next line of code following the block.
• Driving analogy: driving along the 401, you may choose to go into a service
centre, or you may just drive on by, but either way you eventually arrive at
your destination.

4 INFO6066
Software and Information Systems Testing

Coding Style…
• NOTE: most programmers put curly braces around every if block
statement, even if there is only 1 statement to execute. DO THIS, AS THIS IS
CONSIDERED EXCELLENT CODING STYLE!
• Example:

if (number1 > 5)
{
System.out.print("number1 value is greater than 5.");
} //end if

• Doing this clearly specifies exactly what happens if the condition tests true.
It’s good coding style. DO IT!
• If there are multiple statements to be executed in the if block, then you
must put them inside curly braces.

5 INFO6066
Software and Information Systems Testing

if-else Statements
• In an if statement , the block statement is executed if condition is TRUE.
• If false, the next statement after the block is executed.
• Q. What if you want some specific action to occur if condition tests FALSE?
• A. Can use an if…else statement to provide an action in case of a FALSE test.
• An if-else structure is called a double-selection structure because it
executes one block of code if the condition evaluates to true, and a
different block of code if the condition evaluates to false.
• Driving analogy: You come to a stop sign at a ‘T’ intersection, and you have
to turn either left or right.

6 INFO6066
Software and Information Systems Testing

Expanding an if to an if-else
• if ( boolean expression)
{
//block statement(s) for true case;
}
else
{
//block statement(s) for false case;
}//end if-else

• Again, for clarity, use curly braces around each code block.
• Note: also indent block code 2 spaces inside braces ( this is good coding
style and makes it easier to follow)

7 INFO6066
Software and Information Systems Testing

Example if-else
• int number = input.nextInt( );
if (number >100)
{
System.out.println (number + " is greater than 100");
}
else
{
System.out.println (number + " is less than 100");
}
• We can also test for more than two conditions, or cases, by
expanding the if-else to an if-else-if-else statement. See next slide.

8 INFO6066
Software and Information Systems Testing

Checking multiple conditions using if-else-if statements


• if ( boolean expression)
{
//statement 1 here
}
else if ( boolean expression)
{
// statement 2 here
}
else
{
//statement 3 here
}
• Can be used to evaluate as many values for expression as needed, and you can
implement different actions depending on what the value is.
• Driving analogy: you drive into a traffic circle that has multiple exits.

9 INFO6066
Software and Information Systems Testing

Example if-else-if for calculating letter grades…


if (testScore >= 90)
{
• The conditional expression may include
grade = "A+"; the use of a relational operator such as
} >=.
else if (testScore >=80) • Could also put a logical operator in the
{
grade = "A";
condition, such as the AND operator… &&
} •
else if(testScore >=70) if (testScore>=80 && testScore <=100)
{
grade = "B"; • read this as “If test score is greater than or
}
else if(testScore >=60) equal to 80 AND test score is less than or
{ equal to 100…
grade = "C"; • would test to see if the value is within the
}
else
range from 80 to 100.
{ • We’ll look at the logical operators AND
grade = "F"; and OR in slide set 2-3A
}

10 INFO6066
Software and Information Systems Testing

Preferred Style for if-else statement for easy reading


if (testScore >= 90)
{
grade = "A+";
}
else if (testScore >=80)
{
grade = "A";
}
else if(testScore >=70)
{
grade = "B";
}
else if(testScore >=60)
{
etc. etc.
}

11 INFO6066
Software and Information Systems Testing

Boolean or Logical Operators


• From our work on conditional statements ( ‘if’ and if’-else’) we know that
the expression in an ‘if’ statement evaluates to either a boolean true or
false value.

if(userAge > 30)


{
System.out.print("Man, you are older than dirt!");
}
• This is good for checking just one condition at a time.
• Q. What if you want to check two or more conditions at a time?
• A. It’s possible, but you have to make use of LOGICAL operators in your if
(expression).

12 INFO6066
Software and Information Systems Testing

Logical Operators, cont’d


• Example: suppose you want to do an app that determines what letter
grade a student will receive.
• This is a “range check” type of operation, which is used to see if a value is
within a certain range. Let’s start at the D level.
• To qualify as a D, a mark must be 50 or greater, and it must be less than 55.
If it 55, then the mark is a D+.
• So, two conditions have to met here:
1) mark must be >= 50, AND
2) mark must be < 55
• When two conditions must both be true at the same time, then we use the
logical AND operator to test that both are true.

13 INFO6066
Software and Information Systems Testing

The Logical AND operator…


• Pseudocode would look like this:

if (mark >= 50 && mark <55)


then award a mark of ‘D’

• The logical AND indicates that both conditions must be true in order for the
overall if expression to return a value of true. (T!)
• If either condition is false, or both are false, then the overall if expression
evaluates to false. (T!)
• See the TRUTH TABLE for the logical AND operator on the next slide…

14 INFO6066
Software and Information Systems Testing
Truth Table for Logical AND (X)
Condition One OPERATOR Condition Two RESULT

FALSE && FALSE FALSE

TRUE && FALSE FALSE

FALSE && TRUE FALSE

TRUE && TRUE TRUE

 The only way to get a TRUE result from a


logical AND operation is for both
conditions to be true. (T!)

15 INFO6066
Software and Information Systems Testing

The Logical OR operator


• Sometimes we want to test multiple conditions at the same time, but only
one condition has to be met in order to proceed.
• Example: suppose that to qualify for a particular job, an applicant has to
have either a college Diploma in Networking or a CISCO CCNP certificate.
• In pseudocode, it would look like this:
if (qualification == “diploma” OR qualification == “CCNP”)
then person is qualified to apply.
• If the applicant meets either qualification, then they qualify for the job.
Only one of the two conditions have to be met.
• See the TRUTH TABLE for the LOGICAL OR operator on next slide.

16 INFO6066
Software and Information Systems Testing
Truth Table for Logical OR (+)
Condition One OPERATOR Condition Two RESULT

FALSE || FALSE FALSE

TRUE || FALSE TRUE

FALSE || TRUE TRUE

TRUE || TRUE TRUE

 There are three possible ways to get a


TRUE result from a logical OR operation.
 The only way to get a FALSE is for both
conditions to be FALSE. (T!)
17 INFO6066
Software and Information Systems Testing

What do AND and OR look like in Java code?


• In Java, the logical AND operator is the double ampersand ‘&&’
• Ex. if(userInput > =50 && userInput <55)
{
System.out.println(“That mark is a ‘D’);
}

• The logical OR symbol is the double ‘pipe’ symbol (also called the ‘broken
vertical bar’) which is the shifted backslash on most keyboards.
• if(qualification.equals(“diploma”) || qualification.equals(“CCNP”)
{
System.out.println(“You qualify for the job”);
}

18 INFO6066
Software and Information Systems Testing

The NOT or Negation Operator ‘!’

• The exclamation mark (also called the ‘bang!’ operator) is the logical NOT
operator.
• It simply reverses the value of any Boolean operand it is placed in front of.
• Example:
– Given that the integer variable age contains 21:
– age > 15 is TRUE
– !(age > 15) is FALSE

If you use it with the java keywords ‘true’ and ‘false’, then
– !true would be FALSE
– !false would be TRUE

19 INFO6066
Software and Information Systems Testing

Evaluating Multiple Values: The switch Statement


• For evaluating a value against more than four or five cases, a switch
statement may be a better choice than an if statement.
• Can be a little cleaner and easier to follow.
• However, you are more limited in what you can use in the test expression.
• A switch statement can evaluate specific integral or whole number values,
but not decimals values such as 2.5.
• a switch can evaluate specific char values (single characters) and as of JDK
1.7, it can also now evaluate String values.
• a switch cannot use relational operators such as > or <. You can only test
for equality using the equality operator “==“. (T!)

20 INFO6066
Software and Information Systems Testing

Switch Analogy…
• There is a famous TV game in North America called“Let’s Make a Deal!”,
hosted by Wayne Brady
• In the grand finale to each show, contestants could choose to exchange
their earlier prize for a chance to win the “big prize” of the day.
• Contestants would select one of three doors on the stage to determine
what their final prize would be. Prizes might be:
• Door number one: a car
• Door number two: a tropical cruise vacation
• Door number three: a live goat (the booby prize)
• Consolation prize was often some sort of “house warming gift”

21 INFO6066
Software and Information Systems Testing

Set it up as a switch-case
switch(doorNumber)
{
case 1: // 1 is the value held by variable doorNumber
prize = "money";
break; // break command is the “exit” from the switch structure
case 2: // 2 is the value held by variable doorNumber
prize = "tropical cruise";
break;
case 3: // 3 is the value held by variable doorNumber
prize = "live goat";
break;
default:
prize = "house warming gift";
} //end switch

22 INFO6066
Software and Information Systems Testing

switch statement syntax


• value 1, value 2 must be integral values of
switch(switch-expression)
type byte, char, short, or int
{
case value 1: statement 1; • New for JDK 1.7: Strings may now be used
break; as well!
case value 2: statement 2; • Can’t be float or double
break; • Can’t use a relational operator like this:
…and so on…
//optional case >=90:
• must just be like this:
default :statement; case 1: statement1
• Note that the switch statement is one of
} //end switch the few places in Java where we use the
colon character “:”
…next line of code

23 INFO6066
Software and Information Systems Testing

switch…
• input value will “fall through” the switch cases till it finds a matching value.
• That code block will execute, and then a break occurs. This kicks us out of
the switch statement entirely, and execution goes to next line following
switch statement.
• break keyword is not needed after very last statement in switch.
• Default case is optional. Is executed if input value does not match any of
the above cases.
• Common error in switch statements is forgetting to put in a break
statement after a particular case statement.
• If you forget the break statement after a case, then the next case
statement in the stack will also execute( try this to see it!)

24 INFO6066
Software and Information Systems Testing
switch Example using ints

//user enters an integer value for int variable washCycle


switch(washCycle)
{
case 1: typeOfWash = "Cold water for wool";
break;
case 2: typeOfWash = "Warm water for synthetics";
break;
case 3: typeOfWash = "Warm water for colours";
break;
case 4: typeOfWash = "Hot water for whites";
break;
default: typeOfWash = "Hot water, extra bleach";
}//end switch

25 INFO6066
Software and Information Systems Testing

switch Example using chars

• //user enters a char value for char variable choice on a multiple choice
quiz program
switch(choice)
{
case ‘A’: resultString = “Incorrect. C was correct answer";
break;
case ‘B’: resultString = “Incorrect. C was correct answer";
break;
case ‘C’: resultString = “You are correct!";
break;
case ‘D’: resultString = “Incorrect. C was correct answer";
break;
default: resultString = “Please enter A,B,C, or D…";
}//end switch
26 INFO6066
Software and Information Systems Testing

switch Example using Strings


• //user enters a String value for String variable name for a new baby boy to get the
computer’s opinion of their choice.
switch(name)
{
case “Mike”: resultString = “Excellent choice for your new baby boy!";
break;
case “Dev”: resultString = “Not bad, but I like ‘Mike’ better…”;
break;
case “Jim”: resultString = “It works, but have you considered ‘Mike’?”;
break;
case “Omkar”: resultString = “Could be an Indian name…how about ‘Mike’?”;
break;
default: resultString = “Just name your kid Mike…";
}//end switch
• NOTE: the strings must match exactly, so letter case is important.

27 INFO6066
Software and Information Systems Testing

Homework – Chapter Three


3.1 If-else branches (general) 3.11 Switch statements
3.2 Detecting equal values with branches 3.12 Boolean data type
3.3 Detecting ranges with branches 3.13 String comparisons
(general) 3.14 String access operations
3.4 Detecting ranges with branches
3.15 Character operations
3.5 Detecting ranges using logical
3.16 More string operations
operators
3.17 Conditional expressions
3.6 Detecting ranges with gaps
3.7 Detecting multiple features with
3.18 Floating-point comparison
branches 3.19 Short circuit evaluation
3.8 Common branching errors 3.20 Java example: Salary calculation
3.9 Example: Toll calculation with branches
3.10 Order of evaluation 3.21 Java example: Search for name
using branches

28 INFO6066

You might also like