CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)Lecture Set #5:If StatementsLast time:1.Variables and types2.Expressions in Java3.User input with Scanner objectsThis set:1.if statementsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)1Control Flow and ConditionalsControl flow: the order in which statements are executedGeneral rule: top to bottomConditional statements permit control flow to be dependent on (true/false) conditionsifif-elseCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)2The if StatementForm:if ( <boolean-expression> ){<statement>}Example:if (inchesOfSnow > 7) {System.out.println( “Go home” );}The println statement is executed only if the variable “inchesOfSnow” is greater than 7Otherwise, it is skippedboolean expression =a condition: true or falsestatementCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)3Example 6public class Example6 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter an integer: ");int i = sc.nextInt();if (i < 0){System.out.println("That was a negative number!");}System.out.println("The number was " + i);}}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)4The if-else StatementForm:if ( <condition> ){<statements 1>;}else{ <statements 2>;}Example:if (inchesOfSnow > 7) {System.out.println(“Go home”);} else {System.out.println(“Go to school”);}If “inchesOfSnow” > 7, the first println statement is executed and the second is skippedOtherwise (i.e. inchesOfSnow ≤ 7), the first println statement is skipped and the second is executedCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)5Indentation Convention for if-elseThe if-else class of statements should have the following form: if (condition) {statements; } if (condition) {statements; } else { statements; }CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)6BlocksWhat happens?if (i > 10) i = 10; saturate = true; Desired: both i, saturate are set only when i > 10Actual: only the i=10 statement is dependantOnly one statement can be associated with ifThe saturate assignment statement is not part of the ifBlocks solve this problemCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)7BlocksWhat happens?if (i > 10) i = 10; saturate = true; elsek = 100;Desired: both i, saturate are set only when i > 10Actual: syntax errorOnly one statement can be associated with ifThe saturate assignment statement is not part of the ifThe else can’t find the if it belongs toBlocks solve this problem alsoCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)8What Blocks AreBlocks are sequences of statements “glued together” into oneForm:{<statement 1>;<statement 2>;…}Example:if (i > 10) {i = 10;saturate = true;} else {i = i+1;}blockblockCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)9Indentation Conventions for BlocksEitherif (…) {statement 1;statement 2;…}Orif (…){statement 1;statement 2;…}This is what we will use (Sun code convention)CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)10See Sun Code Conventions on Resource Page!http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.htmlCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)11Java and White SpaceYou can add:carriage returnsspacestabswherever you want in JavaProperly used, this makes your program easier to read and understandCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)12Example 7public class Example7 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter an integer: ");int i = sc.nextInt();if (i < 0) {System.out.println("That was a negative number!");} else {System.out.println("That was a non-negative number!");}System.out.println("The number was: " + i);}}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)13Logical OperatorsUsed for forming more complex conditions.“and” &&if ( temp >= 97 && temp <= 99 ) {System.out.println( “Patient is healthy” );}“or” ||if ( months >= 3 || miles >= 3000 ) {System.out.println( “Change your oil” );}“not”: !if ( ! phone.equals( “301-555-1212” ) ) {System.out.println( “Sorry, wrong number” );}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)14Example 8public class Example8 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter an integer: ");int i = sc.nextInt();if (i < 0) {System.out.println("That was a negative number!");System.out.println("I prefer positive ones, so I'll fix it...");i = -i;} else {System.out.println("That was a positive number!");System.out.println("That makes me happy.");}System.out.println("The number is now " + i);}}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)15Example 9public class Example9 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("Enter an integer from 1 to 10: ");int i = sc.nextInt();if (i >= 1 && i <= 10) {System.out.println("Good job!");} else {System.out.println("You didn't follow instructions!");}}}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)16Statement Constructors and Nestingif, if-else, {…} are statement constructorsThey take statement(s) and convert them into a new statementExample:if (i >= 1 && i <= 10) {System.out.println("Good job!");} else {System.out.println(“Oops!");}Two “sub-statements” come inA single big statement (if … else …) comes outImplications: if statements, etc. can also appear inside (“be nested within”) one anotherCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)17Java, Eclipse and UninitializedVariablesEclipse will complain if you try to use an uninitialized variable:int i;System.out.println (“i is “ + i);What is value of i?This feature interacts strangely with if/else statements sometimesGood programming practice: always initialize new
View Full Document