Lecture 9b/10 Instructor: Craig Duckett A Quick Note About: Assignment 4 (BASIC or ADVANCED) I will “officially” be going over Assignment 4 (Basic or Advanced) on Wednesday, March 2nd There is still way too much that we need to look at before we look at Assignment 4 (especially Arrays) so hold tight for another week. Please Note: Even though we’ll be looking at Assignment 4 on March 2nd h you’re still going to need the information from Lecture 17 (March 7th) to be successful at it. If you are itching to get started on Assignment 4 you want to look through all the material one your own through Lecture 17. This Monday, February 29th, I'll be giving you a Gentle Introduction to Arrays, so make sure to be here for that Lecture 14/15 Topics • • • • • for statement (loop) do-while loops Nested loops cascading-ifs switch statements Today Next Lecture • CHECK OUT PROBLEM/SOLUTIONS IN LECTURE 14 REGARDING USE OF INSTANCE VARIABLE FROM ONE CLASS IN ANOTHER CLASS And now . . . The Quiz A Quick Word About Static No, not these kinds of static public class FileName4 extends Object { public static void main(String[] args) { System.out.println( “I printed!"); } Class … but no Object ! What the hay? } The main method is going to run whether it contains an instance (object) of a class or not. It is declared static for just such this reason—static means that main does not need an instance (object) of the class that contains it to be created in order for main to run, because main is set up to be its own instance. In this way, main acts like the starter on a car, it doesn’t need a starter to start the starter…it is the starter. Interesting note: you can compile your Java program without a main method, you just can’t run it! (just like you can build a car without a starter, but you can’t start it without the starter). See FileName5.java for example. Now, if you are wanting to use other classes (their “actions” and “attributes”) down in main, then you do need to create an instance of those classes ( a named object) that can actually do the something (whatever that something is) that you want done. For instance (pun intended!) when we are using the Becker Robot class, then we need to create a named instance of the Robot class (e.g., a Robot object called “Karel” or “Jo” or “Mary”) if we want to see any activities and actions done (move, pickThing, putThing, etc). Without an Object calling the actions, these methods only remain unused and potential… This will not compile (there is no object to do the action) public class StaticDemo { int my_member_variable = 99999; public static void main (String args[]) { // Access a non-static member from static method System.out.println ("This generates a compiler error :-( " + my_member_variable); } } This will compile (there is an object called demo to do the action) public class NonStaticDemo { int my_member_variable = 99999; public static void main (String args[]) { NonStaticDemo demo = new NonStaticDemo(); // Access member variable of demo System.out.println ("This WON'T generate an error! --> " + demo.my_member_variable ); } } Static Defined: In Java, a static member is a member of a class that is not associated with an instance (object) of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance (object). Static Method A static method does not need an object to call it. It can call itself! You there? I’m here! One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields. public class FileName3 extends Object { Class public static int printNum() { System.out.println("Going to print, some number of times!"); Static Method int howManyPrints = 0; while(howManyPrints < 2) { System.out.println("Printing!"); howManyPrints++; // This is a basic counter } return howManyPrints; } public static void main(String[] args) { int num = 0; num = printNum(); // <-- Notice this method call has no object System.out.println( "The method printed " + num + " times!"); } Method is called in main and a value is returned and put into num } Example: FileName3.java Some Additional Static Examples • StaticDemo1.java Does Not Compile • StaticDemo2.java Does Compile • StaticDemo3.java A Static Method Public (or ‘Instance’) Method A public method does need an object to call it. It can not call itself! Therefore, in order to use a public method down in main you need to create an instance of an object from the class that contains the method. I’m an Object! I’m a Method! Glad you Called! The for statement (loop) “For as long as this condition is true . . . d o s o m e t h i n g .” The for statement (loop) The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: Semi-colon for(initiating Semi-colon statement; conditional statement; next statement) { // body statement(s); } “For as long as this condition is true . . . d o s o m e t h i n g .” The for statement (loop) for (initial statement; conditional; next statement // usually incremental { statement(s); } “ F o r a s l o n g a s t h i s i s t r u e . . . d o s o m e t h i n g .” class ForLoopDemo { public static void main(String[] args) { for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); } } } The output of this program is: Count Count Count Count Count Count Count Count Count Count is: is: is: is: is: is: is: is: is: is: 1 2 3 4 5 6 7 8 9 10 The for statement (loop) There are three clauses in the for statement. • • • The init-stmt statement is done before the loop is started, usually to initialize an iteration variable (“counter”). After initialization this part of the loop is no longer touched. The condition expression is tested before each time the loop is done. The loop isn't executed if the Boolean expression is false (the same as the while loop). The next-stmt statement is done after the body is executed. It typically increments an iteration variable (“adds 1 to the counter”). for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); } The for Loop initialization; while(condition) { statement; } for(initialization; condition; increment) { statement; } The for loop is shorter, and combining the intialization, test, and increment in one statement makes it easier to read and verify that it's doing what you expect. The for loop is better when you are counting something. If you are doing something an indefinite number of times, the while loop may be the better choice. while loop class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } for loop class ForLoopDemo { public static void main(String[] args) { for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); } } } while loop class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } for loop class ForLoopDemo { public static void main(String[] args) { for(int count = 1; count < 11; count++) { System.out.println("Count is: " + count); } } } SEE: for_while_test.java The Do-While Loop do-while loops The Java programming language also provides a do-while statement, which can be expressed as follows: do { statement(s) } while (expression); The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } } while loop EVALUATES AT THE TOP class WhileDemo { public static void main(String[] args) { int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } for do-while loop EVALUATES AT THE BOTTOM class DoWhileDemo { public static void main(String[] args) { int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } SEE: for_while_do_while _test.java } Nested Loops We will look at nested loops today and again next lecture. A “Box” of Stars and More Let’s imagine we want to make a “box” of stars (asterisks). How might we go about doing that? ******* ******* ******* ******* ******* • • • • • • rows_of_stars_01 rows_of_stars_02 Rows_of_stars_03 NestWhileTest.java NestForWhileTest.java NestedForsClock.java REFRESHER: The if-else Statement if(Boolean_expression){ statement 1 //Executes when true }else{ //<-- No Conditional statement 2 //Executes when false } public class IfElseTest { public static void main(String args[]) { int x = 30; if( x < 20 ){ System.out.print(“The number is less than 20."); }else{ System.out.print(“The number is NOT less than 20!"); } } } The if-else Statement if(Boolean_expression){ statement 1 //Executes when true }else{ // <--No Conditional statement 2 //Executes when false } Now, this works great if you’re only testing two conditions, but what do you do if you have more than two conditions? What if you have three conditions, or four, or five? Several if Statements You could create a whole bunch of if statements to look for and test a particular condition, and this is perfectly acceptable, although this might get unwieldy if you have several conditions, say ten or more to look through. if(Boolean_expression_01) { statement//Executes when true } if(Boolean_expression_02) { statement//Executes when true } if(Boolean_expression_03) { statement//Executes when true } if(Boolean_expression_04) { statement//Executes when true } if(Boolean_expression_05) { statement//Executes when true } Several if Statements int grade = 98; if(grade >=0 && grade < 60) { System.out.println(”Sorry. You did not pass.”); } if(grade >= 60 && grade < 70) { System.out.println(”You just squeaked by.”); } if(grade >= 70 && grade < 80) { System.out.println(”You are doing better.”); } if(grade >= 80 && grade < 90) { System.out.println(”Not too bad a job!”); } if(grade >= 90 && grade <= 100) { System.out.println(”You are at the top of your class!”); } “Nested if-elses" It is common to make a series of tests on a value, where the else part contains only another nested if statement. If you use indentation for the else part, it isn't easy to see that these are really a series of tests which are similar. This is traditional syntax, but there’s actually a cleaner way to do this in Java. int grade = 68; if(grade >=0 && grade < 60) { System.out.println("Sorry. You did not pass."); } else { if(grade >= 60 && grade < 70) { System.out.println("You just squeaked by."); } else { if(grade >= 70 && grade < 80) { System.out.println("You are doing better."); } else { if(grade >= 80 && grade < 90) { System.out.println("Not too bad a job!"); } else //(grade >= 90 && grade <= 100) { System.out.println("You are at the top of your class!"); } } } } And how about all those squiggles! "Cascading-if" if…else if…else if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true }else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }else { // <-- No Conditional //Executes when none of the above conditions are true. } if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true }else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true }else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true }else { // <-- No Conditional //Executes when none of the above conditions are true. } Text "Cascading-if" if…else if…else So, contrary to our typical formatting style of indenting to the braces, it is better to write them at the same indentation level by writing the if on the same line as the else. int grade = 68; if(grade >=0 && grade < 60) { System.out.println("Sorry. You did not pass."); } else if(grade >= 60 && grade < 70) { System.out.println("You just squeaked by."); } else if(grade >= 70 && grade < 80) { System.out.println("You are doing better."); } else if(grade >= 80 && grade < 90) { System.out.println("Not too bad a job!"); } else // <-- No conditional { System.out.println("You are at the top of your class!"); } if (this.frontIsBlocked()) { this.turnAround(); } else if (this.canPickThing()) { this.turnRight(); } else if (this.leftIsBlocked()) { this.turnLeft(); } else { this.move(); } The Switch Statement switch statement The switch statement is similar to the cascading-if statement in that both are designed to choose one of several alternatives. The switch statement is more restrictive in its use, however, because it uses a single value to choose the alternative to execute. The cascading-if can use any expressions desired. This restriction is also the switch statement’s strength: the coder knows that the decision is based on a single value. switch ( expression { case value1 : //statement(s) break; case value2 : //statement(s) break; case value3 : //statement(s) break; default : //statement(s) } ) when expression == value1; when expression == value2; when expression == value3; if no previous match; switch statement int score = 8; switch (score) { case 10: System.out.println ("Excellent."); case 9: System.out.println (“Well above average."); break; case 8: System.out.println (“Above average."); break; case 7: case 6: System.out.print ("Average. You should seek help."); break; default : System.out.println ("Not passing."); } Now, this switch written as is will work provided the user enters the correct data and in the correct range, but it will not properly catch improper data or data that is outside the range. What might you do to properly handle values that are outside of the range? Add so if statements to the default perhaps! switch statement int score = 8; switch (score) { case 10: System.out.println ("Excellent."); case 9: System.out.println (“Well above average."); break; case 8: System.out.println (“Above average."); break; case 7: case 6: System.out.print ("Average. You should seek help."); break; default : if(score > 11 || score < 0) { System.out.println ("Score entered is not in range!"); } else { System.out.println (“Less than 6. Not passing."); } } Switch INSTRUCTOR NOTE: Show Examples SwitchExample.java SwitchExample2.java LECTURE 9b/10: ICE 42