Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 14/15 Instructor: Craig Duckett. 2 ANNOUNCEMENTS For various reasons, the Cascadia Faculty web server occasionally goes down, making it impossible.

Similar presentations


Presentation on theme: "Lecture 14/15 Instructor: Craig Duckett. 2 ANNOUNCEMENTS For various reasons, the Cascadia Faculty web server occasionally goes down, making it impossible."— Presentation transcript:

1 Lecture 14/15 Instructor: Craig Duckett

2 2 ANNOUNCEMENTS For various reasons, the Cascadia Faculty web server occasionally goes down, making it impossible to get to my BIT web sites to check files, download assignments, use Student Tracker, etc. As such I have mirrored my BIT web sites on my personal web server at programajama.com. To access courses hosted on programajama.com: http://www.programajama.com/courses To access StudentTracker on homeworkhandin.com: http://homeworkhandin.com/StudentTracker/ If you find that the Cascadia email is temporarily down (like it was this past weekend), then you can email me at clduckett@gmail.com until the Cascadia email servers are back up and running.clduckett@gmail.com

3 3 Assignment 3 Graded! Returned! Assignment 3 Revision (LECTURE 16) Tuesday, November 24, in StudentTracker by midnight Assignment 4 (LECTURE 20) Tuesday, December 8 Assignment 4 Revision (LECTURE 21) Thursday, December 10 Assignment Dates (By Due Date)

4 Assignment 4 (BASIC or ADVANCED) I will “officially” be going over Assignment 4 (Basic or Advanced) on Tuesday, November 24 th 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 November 24 th you’re still going to need the information from Lecture 17 (December 1 st ) 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 Thursday, November 18 th, I'll be giving you a Gentle Introduction to Arrays, so make sure to be here for that A Quick Note About:

5 Lecture 14/15 Topics for statement (loop) do-while loops Nested loops cascading-ifs switch statements Today Thursday

6 And now... TheQuiz

7 A Quick Word About Static No, not these kinds of static

8 public class FileName4 extends Object { public static void main(String[] args) { System.out.println( “I printed!"); } } Class 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… 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… … but no Object ! What the hay?

9 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 not compile (there is no object 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 ); } } This will compile (there is an object called demo to do the action)

10 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).

11 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.

12 public class FileName3 extends Object { public static int printNum() { System.out.println("Going to print, some number of times!"); 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!"); } } Class Static Method Method is called in main and a value is returned and put into num Example: FileName3.java

13 Some Additional Static Examples StaticDemo1.java Does Not Compile StaticDemo2.java Does Compile StaticDemo3.java A Static Method

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

15 The for statement (loop) “For as long as this condition is true... do something.”... do something.”

16 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: for (initiating statement ; conditional statement ; next statement) { // body statement(s); } “For as long as this condition is true... do something.”... do something.” Semi-colon

17 The for statement (loop) for (initial statement; conditional; next statement // usually incremental { statement(s); } 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 is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 “For as long as this is true... do something.”

18 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); }

19 The for Loop

20 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.

21 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); }

22 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

23 The Do-While Loop

24 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); }

25

26 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

27 Nested Loops We will look at nested loops today and again on Thursday NestWhileTest.java NestForWhileTest.java NestedForsClock.java

28 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!"); }

29 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?

30 Several if Statements 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 } 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.

31 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!”); }

32 “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 && grade = 70 && grade = 80 && grade = 90 && grade <= 100) { System.out.println("You are at the top of your class!"); } } } } And how about all those squiggles!

33 "Cascading-if" if…else if…else Text 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. }

34 "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 && grade = 70 && 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!"); }

35 if (this.frontIsBlocked()) { this.turnAround(); } else if (this.canPickThing()) { this.turnRight(); } else if (this.leftIsBlocked()) { this.turnLeft(); } else { this.move(); }

36 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) when expression == value1; break; case value2 : statement(s) when expression == value2; break; case value3 : statement(s) when expression == value3; break; default : statement(s) if no previous match; }

37

38 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."); } switch statement 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.

39 Switch INSTRUCTOR NOTE: show example SwitchExample.java SwitchExample2.java

40 ICE: Switch http://faculty.cascadia.edu/cduckett/bit115/ICEsByTopic/240_Switch/Exercises.html

41 Introduction to Arrays What is an Array? So far, you have been working with variables that hold only one value. The integer variables you have set up have held only one number (and later in the quarter we will see how string variables will hold one long string of text). An array is a collection to hold more than one value at a time. It's like a list of items. Think of an array as like the columns in a spreadsheet. You can have a spreadsheet with only one column, or several columns. The data held in a single-list (one-dimensional) array might look like this: grades 0100 189 296 3100 498

42 Introduction to Arrays Now, the way we might have declared data like this up until now is to do something along these lines: int value1 = 100; int value2 = 89; int value3 = 96; int value4 = 100; int value5 = 98; However, if we knew before hand that we were going to be declaring six int integers (or ten, or fifteen, etc), we could accomplish the same type of declaration by using an array. grades 0100 189 296 3100 498 NOTE NOTE: Arrays must be of the same data type, i.e., all integers (whole numbers) or all doubles (floating-point numbers) or all strings (text characters)—you cannot “mix-and-match” data types in an array. To set up an array of numbers like that in the table above, you have to tell Java what type of data is going into the array, then how many positions the array has. You’d set it up like this: int[ ] grades;

43 Introduction to Arrays grades 0100 189 296 3100 498 int[ ] grades; The only difference between setting up a normal integer variable and an array is a pair of square brackets after the data type. The square brackets are enough to tell Java that you want to set up an array. The name of the array above is grades. Just like normal variables, you can call them almost anything you like (except Java defined keywords). The square brackets tells Java that you want to set up an integer array. It doesn't say how many positions the array should hold. To do that, you have to set up a new array object: grades = new int[5]; In between the square brackets you need the pre-defined size of the array. The size is how many positions the array should hold. If you prefer, you can put all that on one line: int[ ] grades = new int[5];

44 Introduction to Arrays grades 0100 189 296 3100 498 You can also declare the int separately and call it by its given name, like this: int summer2012 = 5; int[ ] grades = new int[summer2012]; (Whether you call the number inside the brackets or a named variable is up to your particular style of coding and preference.) So we are telling Java to set up an array with 5 positions in it. After this line is executed, Java will assign default values for the array. Because we've set up an integer array, the default values for all 5 positions will be zero ( 0 ). To assign values to the various positions in an array, you do it in the normal way: grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; If you know what values are going to be in the array, you can set them up like this instead: int[ ] grades = { 100, 89, 96, 100, 98 }; // Java treats as a // new instance grades [0] = 100; grades [1] = 89; grades [2] = 96; grades [3] = 100; grades [4] = 98; This is called the index Length of the array is equal to the number of slots declared {

45 Introduction to Arrays grades 0100 189 296 3100 498 When you declare an array with a given data type, name and number, like grades = new int[5]; You are reserving a collection space in memory by that name, sized according to data type, and the large enough to separately contain the data for the declared number. 01234 32-bits 32-bit32-bits 00000 grades (a named reserved space set aside to hold exactly five 32-bit elements all initializing to zero) array element index  space reserved for data  value stored in element  01234 100899610098 grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98;

46 Introduction to Arrays: Example import java.util.*; public class Array_Demo extends Object { public static void main(String[] args) { // Setting up the integer 5-element array: int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; // Of course you could have done it this way: // int [] grades = {100, 89, 96, 100, 98}; int i; for(i = 0; i < grades.length; i++) { System.out.println("Grade " + (i + 1) + " is: " + grades[i]); } } }


Download ppt "Lecture 14/15 Instructor: Craig Duckett. 2 ANNOUNCEMENTS For various reasons, the Cascadia Faculty web server occasionally goes down, making it impossible."

Similar presentations


Ads by Google