If-Else Statements and Logical Expressions Logical Expressions need to code for certain conditions conditions can be exact, or wide ranging computer will actually match up conditions with code you create watch for conditions that are very much alike prepare for ANY possible condition, even if you think it’s impossible types in coding o if/else’s o if/else –if’s o logical symbols used to compare Condition Statements - if structure o is a single-selection structure because it selects or ignores a single action. if (condition 1) (if) - if/else structure - The if/else structure is called a double-selection structure, because it selects between two different actions. 1
43
Embed
Chap 6 - ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/IfElseNotes.do… · Web viewIf-Else Statements and Logical Expressions Logical Expressions need to code for certain conditions
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
If-Else Statements and Logical Expressions
Logical Expressions need to code for certain conditions conditions can be exact, or wide ranging computer will actually match up conditions with code you create watch for conditions that are very much alike prepare for ANY possible condition, even if you think it’s impossible types in coding
o if/else’so if/else –if’so logical symbols used to compare
Condition Statements- if structure
o is a single-selection structure because it selects or ignores a single action.
if (condition 1) (if)
- if/else structure- The if/else structure is called a double-selection structure, because it selects
between two different actions.- if/else’s’ tells the program to choose and execute one or the other body of code,
depending on the values or conditions
if (condition 1) (if)
else (else)
1
First If-Else Exampleimport java.util.Scanner;
public class IfElse {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);int score;
System.out.println("Please enter the grade you received" );score = sc.nextInt( );
// CONDITIONif(score < 70) // highest probability should go first{
System.out.println("THAT’S NOT GOOD" ); // STATEMENTSSystem.out.println("YOU FAILED" );
}else // then passed{ System.out.println("YOU PASSED" ); }
}// NOTICE ALL OF THE BRACKETS!!! BLOCK LIKE STRUCTURE!!!
IF/ELSE statements return a value!! The computer will evaluate conditions and return true or false
o you (programmer) do nothing to evaluate You (the programmer) create the criteria/condition!
o user does nothing to evaluate will not always reach each condition depending on structure of if
Version #1int finalGrade = 75;
□ if (finalGrade < 70) { System.out.print(“YOU FAILED!!\n”); }□ if (finalGrade > 69) { System.out.print(“YOU PASSED!!\n”); }□ if ((finalGrade > 0) && (finalGrade < 101)){ System.out.print(“You took the class!!\n”); }
Version #2int finalGrade = 75;
□ if (finalGrade < 70) { System.out.print(“YOU FAILED!!\n”); }□ else { System.out.print(“YOU PASSED!!\n”); } // notice no condition
Version #3int finalGrade = 55;
□ if (finalGrade < 70) { System.out.print(“YOU FAILED!!\n”); }□ else { System.out.print(“YOU PASSED!!\n”); } // notice no conditionVersion #4 (Something you haven’t seen just yet)
Truth Tables if we design a project with many possible conditions, we need to make sure we
cover all of those possible conditions!! great way to error check too!!
if( (x && y) || (y || z) )x y z x && y ==A y || z ==B A|| B
0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
2. Determine probably of True or False FINAL answerFalse = ?? / 8 = = ?? % True = ?? / 8 = = ?? %
Ex. (B || C) && !AA B C B || C !A (whole equ.)0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
5
Try a few examples:1. (A && B) || C
A B C A && B || C0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
2. (A && !C) || !B (you may not use all empty columns)A B C0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
3. (!(A || B) && C)A B C A || B !(A || B) && C0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
6
4. (B && (C || A))A B C C || A && B0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
5. (((C || B) || A) && !C)A B C !C C || B || A && !C0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1
Answersb:
7
if-else if = further extension of if-else if-else ifs are used to further break down the condition into a more organized
fashion4 Rules with an If-Else-If structure
1. The structure will always start with an “IF”2. The structure will always END with an “ELSE”3. Everything in between is an else-if4. Last “ELSE” has no condition, since LITERALLY everything else
if-else example if-else if exampleif (condition 1)
else
if (condition 1){ }else if (condition 2)// this else has a couple of conditions{ }else{ }
(if)
(else)
(if)
(else -----------if)
(else)
8
If-Else If Exerciseimport java.util.Scanner;
public class IfElse2 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);int getScore;System.out.println("score?");getScore = sc.nextInt();
if(getScore < 70) // highest probability should go first{
System.out.print("THAT'S NOT GOOD\n");System.out.print("YOU FAILED\n");
1. If we ran the program and entered 89, what will it display?2. If we ran the program and entered 69, what will it display?3. How many else-if(s) could you have?4. How many else (s) could you have?5. How many if(s) could you have?
9
Mechanics of an If-Else is Start from top As soon as we find a match, structure is DONE!!
1. In the structure above, what would be displayed if someone had entered -1237?2. In the structure above, what would be displayed if someone had entered 123?
Nested If-Else statementsHandling nested If-else statements are exactly like what we discussed before, and is easy as long as you understand how regular if-else’s work.
if-else example:
if (condition 1) (if)
(else)else
if (condition 1) (if)if(condition2) (if)
else (else)else (else)
if(condition3) (if)
else (else)
notice that each BRANCH off of one another, and do not mix want to make as many branches as possible to narrow down conditions
Determining structure and outcomes terms
o structures structures start with an if, SOMETIMES end with an ELSE easy way, count the ifs’
o possible outcomes what grades COULD you get from this class?
o Outcome How MANY final grades will you get in this class?
#2 0 if(i < 6)1 { System.out.print(“Mr. L Rocks!!\n”); return; }2 if(i <=8)3 { System.out.println( i + ““); }4 else5 { System.out.println(“used the else”); }
#3 0 if(i < 5)1 { System.out.println(“ less than 5 “); }2 else if(i <=8)3 { System.out.println(“less than or equal to 8”); }4 else5 { System.out.println(“greater than 8”); }
#4 0 if( i < 7)1 { System.out.println(“bad getScore”); }2 else if ( i > 9)3 { System.out.println(“good getScore”); }4 else5 { System.out.println(“ very good”); }6 if( i < 3)7 { System.out.println(“wow you stink!!”); }
return in if statementscan be used inside an if statement- return will break out of the entire FUNCTION
o will end your program, but it may return some value ( true/false/void or a value)
13
Try these examples with different values: i = 3, 6 and 9
0 if(i < 5)1 { System.out.print(“ less than 5 “); }2 else if(i <=8)3 { System.out.print(“less than or equal to 8”); }4 else5 { System.out.print(“greater than 8”); }
i Output?
3
6
9
0 if( i < 7)1 { System.out.print(“bad Score”); }2 else if ( i > 9)3 { System.out.print(“good Score”); }4 else5 { System.out.print(“ very good”); }6 if( i < 3)7 { System.out.print(“wow you stink!!”); }
i Output?
3
6
9
Answersb:
14
Multiple Conditions conditions in if/else if statements don’t exactly follow spoken English Common errors popped up each condition requires 2 values!!
}Please enter a INTEGER choice10Hit 10Please enter a INTEGER choice1Hit 1
21
String input with a menuimport java.util.Scanner;
public class SwitchStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);String value;
System.out.println("Please enter a Presidential (String) choice");value = sc.next();
switch(value){
case "Clinton": System.out.println("One for Hillary"); break;case "Cruz": System.out.println("One for Cruz"); break;default : System.out.print("Don't blame you.");
}}
}Please enter a Presidential (String) choiceLupoliDon't blame you.Please enter a Presidential (String) choiceClintonOne for HillaryPlease enter a Presidential (String) choiceclintonDon't blame you.
22
Cases Handle each action, can handle more than one
One line case statementcase ‘I’: setCount++; break; // for a char choicecase 0: setCount = 0; break; // for a int choice
Two or more line case statementcase ‘D’:
System.out.print(“Displaying answer\n”);total = total + 1;System.out.print( total + “\n”);break; // should ALWAYS HAVE THIS A BREAK AT END OF CASE!!!
Two or more CASES for the same outcomecase ‘Q’:case ‘X’: System.out.print(“Exiting Robot Program\n”); break;// As there was no discontinuation both X or Q will display “Exiting…”
Overall Switch/Case structure and examplechar choice;
System.out.print(“Press X or Q for Exit\n”);System.out.print(“Press L to turn Left\n”);System.out.print(“Press R to turn Right\n”);
choice = sc.next().charAt(0);
switch(choice){
//case ‘3’: when coding for a NUMERIC choicecase ‘L’: System.out.println(“We’re going left!!”); break; // break will take you out of casecase ‘R’: System.out.println(“We’re going right!!”); break; // break will take you out of casecase ‘Q’: // no break, case will continuecase ‘X’: System.out.print(“Exiting Robot Program\n”); break; // break will take you out of casedefault: System.out.print(“Invalid\n”); // if entry was anything but ‘L’, ‘R’, or ‘X’ this is what
}
CASES NOW WORK ON STRINGS!! (In Java 7!!!)
23
Compressed if-else statements debugging or reading code can be hampered by spreading out your code there is no need to put extra lines in between if and else if and elses in SOME cases you can put a statement all in one line there SHOULD be an empty line BEFORE and AFTER your if-else structure
Compression an if-else structureToo Spaced Out Not spaced
if (testscore >= 90){ grade = 'A'; }
else if (testscore >= 80){ grade = 'B'; }
else if (testscore >= 70){ grade = 'C'; }
else if (testscore >= 60){ grade = 'D'; }
else{ grade = 'F'; }
System.out.println("Grade = " + grade);
if (testscore >= 90){ grade = 'A'; }else if (testscore >= 80){ grade = 'B'; }else if (testscore >= 70){ grade = 'C'; }else if (testscore >= 60){ grade = 'D'; }else{ grade = 'F'; }
Redundancy in if-else statements each condition statement should be minimal there should be NO duplication notice the code overall will be shorter anyway
Duplications in an if-else structure (prints)Contains Duplicates Fixed Up