Download presentation
Presentation is loading. Please wait.
1
BIT115: Introduction to Programming
Combo Lecture Lecture 16/17 Instructor: Craig Duckett
2
Assignment Dates (By Due Date)
Assignment 1 (LECTURE 5) Section 1: Wednesday, October 11th Section 3: Thursday, October 12th Assignment 2 (LECTURE 9) Section 1: Wednesday, October 25th Section 3: Thursday, October 26th Assignment 1 Revision (LECTURE 11) Section 1: Monday, November 6th Section 3: Thursday, November 2nd Assignment 2 Revision (LECTURE 13) Section 1: Monday, November 13th Section 3: Thursday, November 9h Assignment 3 (LECTURE 15) Section 1: Monday, November 20th Section 3: Thursday, November 16th Assignment 3 Revision (LECTURE 18) Section 1: Wednesday, November 29th Section 3: Thursday, November 30th Assignment 4 (LECTURE 21) NO REVISION AVAILABLE! Section 1: Monday, December 11th Section 3: Tuesday, December 12th The Fickle Finger of Fate
3
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: To access StudentTracker on homeworkhandin.com: If you find that the Cascadia is temporarily down (like it was this past weekend), then you can me at until the Cascadia servers are back up and running.
4
Assignment 4 (BASIC or ADVANCED)
A Quick Note About: Assignment 4 (BASIC or ADVANCED) I will “officially” be going over Assignment 4 (Basic or Advanced) on LECTURE 18 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 LECTURE 18 you’re still going to need the information from LECTURE 19 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 and Lecture 20. On LECTURE 17 I'll be giving you a Gentle Introduction to Arrays, so make sure to be here for that
5
Lecture 16/17 Topics Assignment Operators for statement (loop)
do-while loops Nested loops cascading-ifs switch statements CHECK OUT PROBLEM/SOLUTIONS IN LECTURE 16 (WHEN UNLOCKED) REGARDING USE OF INSTANCE VARIABLE FROM ONE CLASS IN ANOTHER CLASS Today Next Lecture
6
And now The Quiz
7
Revisit Instance Variables with Examples
See: Lecture 16 Solutions (When Made Available) IVTest1.java Problem: Instance Variable not working in Second Class IVTest2.java Solution 1: Change to One Class Way of Doing Things IVtest3.java Solution 2: Assign Instance Variable to Local Variable IVTest4.java Solution 3: Return Instance Variable to Local Variable Public – Private - Protected
8
More Assignment Operators
int A = 8; int B = 4; int C = 12; int D = 9; More Assignment Operators = Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C = 8 + 4 += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A = -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C – A = *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. B *= A is equivalent to B = B * A = 4 * 8 /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. C /= B is equivalent to C = C / B = 12 / 4 % Modulus operator. Divides left-hand operand by right-hand operand and returns remainder. D%B is goes into 9 twice with 1 remaining.
9
Modulus Example class Remainder {
public static void main (String args[]) { int i = 10; int j = 3; System.out.println("i is " + i); System.out.println("j is " + j); int k = i % j; System.out.println("i%j is " + k); } // Here's the output: i is 10 j is 3 i%j is 1 // The modulus is a good way to determine whether a number is even or odd. X%2 will always return a 0 if X is an even number.
10
A Quick Word About Static
No, not these kinds of static
11
Class Object ! What the hay?
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…
12
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 ); } }
13
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).
14
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.
15
Example: FileName3.java
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
16
Some Additional Static Examples
StaticDemo1.java Does Not Compile StaticDemo2.java Does Compile StaticDemo3.java A Static Method
17
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 a Method! Glad you Called! I’m an Object!
18
The for statement (loop)
“For as long as this condition is true ... do something.”
19
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 Semi-colon for(initiating statement; conditional statement; next statement) { // body statement(s); } “For as long as this condition is true ... do something.”
20
The for statement (loop)
for (initial statement; conditional; next statement // usually incremental { statement(s); } “For as long as this is true ... do something.” 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 class ForLoopDemo { public static void main(String[] args) for(int count = 1; count < 11; count++) System.out.println("Count is: " + count); }
21
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); }
22
The for Loop
23
initialization; while(condition) { statement; } for(initialization; condition; increment) 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.
24
while loop for 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); }
25
while loop for loop SEE: for_while_test.java 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
26
The Do-While Loop
27
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); }
29
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
30
Nested Loops We will look at nested loops today and again next lecture.
31
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 rows_of_stars_04 rows_of_stars_05 NestWhileTest.java NestForWhileTest.java NestedForsClock.java
32
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!"); }
33
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?
34
Several if Statements if(Boolean_expression_01) { statement//Executes when true } if(Boolean_expression_02) if(Boolean_expression_03) if(Boolean_expression_04) if(Boolean_expression_05) 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.
35
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!”);
36
“Nested if-elses" And how about all those squiggles!
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!
37
"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
38
"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!"); }
39
if (this.frontIsBlocked())
{ this.turnAround(); } else if (this.canPickThing()) { this.turnRight(); } else if (this.leftIsBlocked()) { this.turnLeft(); } else { this.move(); }
40
The Switch Statement
42
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; case value3 : //statement(s) when expression == value3; default : //statement(s) if no previous match; }
44
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."); case 7: case 6: System.out.print ("Average. You should seek help."); 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!
45
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."); case 7: case 6: System.out.print ("Average. You should seek help."); default : if(score > 11 || score < 0) System.out.println ("Score entered is not in range!"); } else System.out.println (“Less than 6. Not passing.");
46
break and continue Using break will break you out of a loop or switch, and often stop the program. Sometimes though, you do not want to stop the program, you just want to continue where you left off, or else try going back through the loop again (for example, if the user entered an incorrect value). In that case, you might use continue instead of break, although this might have some unexpected strangeness that goes along with it. Let’s have a look… Demo Examples: break_continue.java break_continue2.java
47
Switch INSTRUCTOR NOTE: Show Examples SwitchExample.java
48
ICE: Switch
49
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 100 1 89 2 96 3 4 98
50
Introduction to Arrays
grades 100 1 89 2 96 3 4 98 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. 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; 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.
51
Introduction to Arrays
grades 100 1 89 2 96 3 4 98 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];
52
Introduction to Arrays
grades 100 1 89 2 96 3 4 98 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; Length of the array is equal to the number of slots declared This is called the index
53
Introduction to Arrays
grades 100 1 89 2 96 3 4 98 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. grades (a named reserved space set aside to hold exactly five 32-bit elements all initializing to zero) array element index 1 2 3 4 32-bits 32-bit space reserved for data value stored in element grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; 1 2 3 4 100 89 96 98
54
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]); } } }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.