chap 6 - ecology labfaculty.cse.tamu.edu/slupoli/notes/java/ifelsenotes.do… · web viewif-else...

43
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

Upload: others

Post on 19-Aug-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

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

Page 2: 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

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!!!

}

Grades Number Line0 69 100

BLOCK LIKE STRUCTURE!!

1 line statements = = { …. statement… }

more than 1 line = = BLS

{… statement 1…… statement 2…… statement 3…… statement 4……}

DO “IF–ELSE IFs” LATER!!!!2

Page 3: 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

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)

int finalGrade = 75;

□ if (finalGrade == 70) { System.out.print(“YOU PASSED!! BARELY!!!\n”); }□ else if (finalGrade > 70) { System.out.print(“YOU PASSED!!\n”); }□ else { System.out.print(“YOU FAILED!!\n”); }

You (the programmer) create the criteria/condition!The computer will decide the outcome!!

3

Page 4: 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

Logical Operators/Gates1/0 or T/F = true and false

A Good example of an OR would be are your keys in the ignition? (x) or are your headlights on? (y), will the alarm sound? (answer)

A Good example of an AND would be did your complete your projects? (x) and did you do well on your tests? (y), will you pass the class? (answer)

NOT, REVERSES each 0/1 T/F statement

Solving Conditions with Logic Gates solve just like a math problem parentheses matter (order of operations!!)

Solving Conditions Example

So are these problems TRUE or FALSE??1. if((8 > 1) || (7 > 8)) ==

4

OR- ||x y answer0 0 00 1 11 0 11 1 1

AND- &&x y answer0 0 00 1 01 0 01 1 1

NOT- !x answer

0 11 0

Page 5: 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

2. if((8 > 9) && (7 > 1)) == 3. if((8 > 9) || (7 > 8)) ==

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

Page 6: 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

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

Page 7: 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

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

Page 8: 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

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

Page 9: 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

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");

}else if((getScore > 88) && (getScore < 90)){ System.out.println("Almost an A!!!"); }else if(getScore > 90){ System.out.println("Teacher’s Pet!!!!"); }else { System.out.println("YOU PASSED"); }

}}

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

Page 10: 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

Mechanics of an If-Else is Start from top As soon as we find a match, structure is DONE!!

Basic Example// 100+ - 90 == A// 89 – 80 == B// 79 – 70 == C// 69 – 60 == D// 59- == F

int grade = 75; // which is a C using our scale

if(grade < 60) { System.out.println( “F, You failed”); }else if(grade < 70) { System.out.println( “below average”); }else if(grade < 80) { System.out.println( “average”); } // stops here!!else if(grade < 90) { System.out.println( “above average”); }else //{ System.out.println( “teacher’s pet”); }

But I don’t wanna!!public class IfElse3{

public static void main(String args[]){

int grade = 75; // which is a C using our scale

if(grade < 60) { System.out.println( "F, You failed"); }if(grade < 70) { System.out.println( "below average"); }if(grade < 80) { System.out.println( "average"); } // stops here!!if(grade < 90) { System.out.println( "above average"); }if(grade < 100){ System.out.println( "teacher’s pet"); }

}}averageabove averageteacher’s pet

10

Page 11: 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

If-Else If Mechanics ExampleCircle/Highlight which condition the program will stop(match) on?Example 1 Example 2 Example 3int grade = 61;

if(grade < 60){ System.out.println( “F, You failed”); }else if(grade < 70){ System.out.println( “below average”); }else if(grade < 80){ System.out.println( “average”); }else if(grade < 90){ System.out.println( “above average”); }else{ System.out.println( “teacher’s pet”); }

int grade = 49;

if(grade < 60){ System.out.println( “F, You failed”); }else if(grade < 70){ System.out.println( “below average”); }else if(grade < 80){ System.out.println( “average”); }else if(grade < 90){ System.out.println( “above average”); }else{ System.out.println( “teacher’s pet”); }

int grade = 91;

if(grade < 60){ System.out.println( “F, You failed”); }else if(grade < 70){ System.out.println( “below average”); }else if(grade < 80){ System.out.println( “average”); }else if(grade < 90){ System.out.println( “above average”); }else{ System.out.println( “teacher’s pet”); }

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?

Even if wrong way!!public class IfElse4 {

public static void main(String[] args) {

int grade = 75; // which is a C using our scale

if(grade > 60) { System.out.println( "F, You failed"); }else if(grade > 70) { System.out.println( "below average"); }else if(grade > 80) { System.out.println( "average"); } // stops

here!!else if(grade > 90) { System.out.println( "above average"); }else //{ System.out.println( "teacher’s pet"); }

}}F, You failed

11

Page 12: 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

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?

12

Page 13: 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

Code Structure count#1 0 if(i < 16)

1 { System.out.print(“Mr. Lupoli Rocks!!\n”);}2 if(i >=8)3 { System.out.println( i + ““); }4 if(i > 8)5 { System.out.println( i + ““); }

#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

Page 14: 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

Try these examples with different values: i = 3, 6 and 9

0 if(i < 16)1 { System.out.print(“Mr. Lupoli Rocks!!\n”);}2 if(i >=8)3 { System.out.print( i + ““); } // display “i” or variable

i???4 if(i > 8)5 { System.out.print( i + ““); }

i Output?3

6

9

0 if(i < 6)1 { System.out.print(“Mr. Lupoli Rocks!!\n”); return; }2 if(i <=8)3 { System.out.print( i + ““); }4 else5 { System.out.print(“used the else”); }

i Output?3

6

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

Page 15: 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

Multiple Conditions conditions in if/else if statements don’t exactly follow spoken English Common errors popped up each condition requires 2 values!!

o x < yo 234 > valueo value1 <= value2

Common Condition ErrorsIncorrect Correct

if( value1 > value2 > value3) if( (value1 > value2) && (value2 > value3))if( value1 < value2 > value3) if( (value1 < value2) && (value2 > value3))if(value1 == value2 > value3 > value4) if( (value1 == value2) && (value2 > value3) && (value3 > value4))

Switch Statements The switch structure is called a multiple-selection structure, because it selects

one of many possible actions. (to be discussed later in semester) USE FOR EXACT VALUES ONLY!!!

When to use whatIf/else Switch/caseif (finalGrade < 90) case ‘A’:if ((score > 90) && ( attendance == 0)) case 0:

Used for Menus ALSO USED TO BE USER (NOT PROGRAMMER) FRIENDLY!!! When to use

o if-else 1-3 actionso switch( ) 3 or more actions

Expression(variable) char or int value (ONLY!!! NOT TO BE USED WITH STRINGS!!!)

15

Page 16: 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

SwitchesSwitch Types

char case/switches int case/switcheschar choice; // used more oftenprintmenu( );

choice = sc.next().toUpperCase().charAt(0);// getting a char (upper case) from the kb

switch(choice){

case ‘L’: moveleft( ); break;case ‘0’ : thisworkstoo(); break;default : System.out.print(“invalid”);

}

int choice;printmenu( );

choice = sc.nextInt();

switch(choice){

case 0: moveleft( ); break;// no quotes around the

// case option if you use // numbers!!!

default : System.out.print(“invalid”);}

switch tells the “case” to match with the “choice”, or whatever is in ( )’s.Will a ‘l’ work on the menu(char)??

16

Page 17: 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

First Example of a Working Switch

import java.util.Scanner;

public class Switch {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);char choice; // used more often

System.out.println("Please enter a choice");choice = sc.next().toUpperCase().charAt(0);// getting a char (upper case) from the kb

switch(choice){

case 'L': System.out.println("Hit L"); break;case '0' : System.out.println("Hit 0"); break;default : System.out.print("invalid");

}}

}

Please enter a choice0Hit 0Please enter a choicedinvalidPlease enter a choice1InvalidPlease enter a choicelHit L

17

Page 18: 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

What did the toUpperCase do??import java.util.Scanner;

public class Switch1 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);char choice; // used more often

System.out.println("Please enter a choice");choice = sc.next().charAt(0);

switch(choice){

case 'L': System.out.println("Hit L"); break;case '0' : System.out.println("Hit 0"); break;default : System.out.print("invalid");

}}

}Please enter a choicelinvalidPlease enter a choiceLHit LPlease enter a choiceLupoliHit L

18

Page 19: 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

What did the breaks do?import java.util.Scanner;

public class Switch4 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);char choice; // used more often

System.out.println("Please enter a choice");choice = sc.next().charAt(0);

switch(choice){

case 'L': System.out.println("Hit L"); _______case '0' : System.out.println("Hit 0");_______case 'j' : System.out.println("Hit J");_______default : System.out.print("invalid");

}}

}LHit LHit 0Hit JInvalidJHit JInvalid

19

Page 20: 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

When is a missing break usefulimport java.util.Scanner;

public class Switch5 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);char choice; // used more often

System.out.println("Please enter a choice");choice = sc.next().toUpperCase().charAt(0);

switch(choice){

case 'A':case 'B':case 'C': System.out.println("Hit 2 on your cellphone");

break;case 'j': System.out.println("Hit J"); break;default : System.out.print("invalid");

}}

}Please enter a choicebHit 2 on your cellphonePlease enter a choiceaHit 2 on your cellphone

20

Page 21: 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

Integer input with a menuimport java.util.Scanner;

public class SwitchInts {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);int value;

System.out.println("Please enter a INTEGER choice");value = sc.nextInt();

switch(value){

case 1: System.out.println("Hit 1"); break;case 2 : System.out.println("Hit 2"); break;case 10 : System.out.println("Hit 10"); break;default : System.out.print("invalid");

}}

}Please enter a INTEGER choice10Hit 10Please enter a INTEGER choice1Hit 1

21

Page 22: 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

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

Page 23: 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

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

Page 24: 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

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'; }

System.out.println("Grade = " + grade);

Ultra Compressed if-else structureif (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);

// then length of each line < 80 characters

24

Page 25: 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

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

if (testscore >= 90){

grade = 'A';System.out.println("Grade = " + grade);

}else if (testscore >= 80){

grade = 'B';System.out.println("Grade = " + grade);

}else if (testscore >= 70){

grade = 'C';System.out.println("Grade = " + grade);

}else if (testscore >= 60){

grade = 'D';System.out.println("Grade = " + grade);

}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'; }

System.out.println("Grade = " + grade);

25

Page 26: 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

Duplications in an if-else structure (variables)Contains Duplicates

salaryWith5percentRaise = salary * 1.05;salaryWith10percentRaise = salary * 1.10;salaryWith15percentRaise = salary * 1.15;salaryWith20percentRaise = salary * 1.20;

if(option == 1.05){ System.out.println("The result is " + salaryWith5percentRaise + ".");}else if(option == 1.10){ System.out.println("The result is " + salaryWith10percentRaise + ".");}else if(option == 1.15){ System.out.println("The result is " + salaryWith15percentRaise + ".");}else // 1.2{ System.out.println("The result is " + salaryWith20percentRaise + ".");}

Fixed UpnewSalary = -1;

if(option == 1.05){ newSalary = salary * 1.05;}else if(option == 1.10){ newSalary = salary * 1.10;}else if(option == 1.15){ newSalary = salary * 1.15;}else // 1.2{ newSalary = salary * 1.2;}

System.out.println("The result is " + newSalary + ".");

So what changed??

26

Page 27: 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

Assignment statements in if conditions Java does NOT allow assignment in conditions

o This is NOT consistent in all languages (C++) Programmers might make the mistake of using a single “=” instead of a “==”

Assignment in a condition (not allowed)The way it was MEANT to be The way it was typed

Type Mismatch Error: cannot convert from int to boolean

Ternary Operator completes basic assignment based on a condition

o condition is TRUE left of ":" is assigned to maxValueo condition is FALSE left of ":" is assigned to maxValue

String result2 = isEven(num2) ? "even" : "odd";int maxValue = (num1 > num2) ? num1 : num2;

27

Page 28: 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

FYI - & vs. && There is a difference!! final answer

o & 0/1o && True/False

&o called the AND bit-wise operator. o used in the comparing of one bit to another bit to see if the outcome will be

a 1 or a 0. (Remember: 1 and 0 are the only possible outcomes when dealing

with bits!)o acts just like a &&, just with bits!!

how it workso first two bits are compared (in yellow below).

Since one of the bits is a 0 the outcome will be a 0. o The second two bits (in purple) are both 1’s, so the outcome is a 1. o And so on...

& Example

0 1 1 1& 1 1 0 1 0 1 0 1

1011100& 0101110

28

Page 29: 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

Answers1. (A && B) || C

A B C A && B || C0 0 0 0 00 0 1 0 10 1 0 0 00 1 1 0 11 0 0 0 01 0 1 0 11 1 0 1 11 1 1 1 1

2. (A && !C) || !B (you may not use all empty columns)A B C !C A && !C !B0 0 0 1 0 1 10 0 1 0 0 1 10 1 0 1 0 0 00 1 1 0 0 0 01 0 0 1 1 1 11 0 1 0 0 1 11 1 0 1 1 0 11 1 1 0 0 0 0

3. (!(A || B) && C)A B C A || B !(A || B) && C0 0 0 0 1 00 0 1 0 1 10 1 0 1 0 00 1 1 1 0 01 0 0 1 0 01 0 1 1 0 01 1 0 1 0 01 1 1 1 0 0

4. (B && (C || A))A B C C || A && B0 0 0 0 00 0 1 1 00 1 0 0 00 1 1 1 11 0 0 1 01 0 1 1 01 1 0 1 11 1 1 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

29

Page 30: 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

#1

i Output?

3 Mr. L Rocks!

6 Mr. L Rocks!

9 Mr. L Rocks!99

#2

i Output?

3 Mr. L Rocks!

6 6

9 used the else

#3

i Output?

3 < 5

6 <=8

9 > 8

#4

i Output?

3 Bad Score

6 Bad Score

9 Very Good

30