Java Programming Function and Advanced Control Structures Phil

  • Slides: 53
Download presentation
Java Programming Function and Advanced Control Structures Phil Tayco San Jose City College Slide

Java Programming Function and Advanced Control Structures Phil Tayco San Jose City College Slide version 1. 2 March 3, 2020

Math Concepts • A common thought about learning software development and coding is that

Math Concepts • A common thought about learning software development and coding is that one must be good at mathematics • This is not necessarily so because as we see with sequences, selection and repetition statements, these tend towards developing logical skills • One area where math and coding do tend to overlap, though, is with functions • The concept is quite similar and is useful in learning how function concepts work in programming languages

Math Concepts f(x, y) = 2 x + y • In math, this function

Math Concepts f(x, y) = 2 x + y • In math, this function has an inherent sequence of steps in the formula – Multiply x by 2 – Take the result and add y • The function completes the formula on the values of x and y and “returns” the result

Math Concepts f(2, 4) = 2(2) + 4 = 8 f(3, 2. 1) =

Math Concepts f(2, 4) = 2(2) + 4 = 8 f(3, 2. 1) = 8. 1 etc. • When we “call” this function, we provide values that are applied within the function to return a result • Notice the second example shows that when we call the function, all that is really seen from our perspective is the final result • Internally, the function multiplies 3 by 2 and adds 2. 1, but what matters is that when we call it with these values, the result that comes back is 8. 1

Math Concepts • This often leads to functions being thought of as “black boxes”

Math Concepts • This often leads to functions being thought of as “black boxes” • Whomever is calling a function, they do so by name, provides value(s) and a value is returned • These 3 parts are critical to identifying how functions work • In general, the 3 parts of the function format are: f(x, y, …) = result • We can break these into parts to formally define how they are used in coding

Math Concepts f(x, y) = result • “f” here is the function name •

Math Concepts f(x, y) = result • “f” here is the function name • In math, a simple letter is often used. In programming, more descriptive names will be seen as more useful • Using descriptive names improves readability of code • At the very least, all functions have a name

Math Concepts f(x, y) = result • The variables in parentheses here imply a

Math Concepts f(x, y) = result • The variables in parentheses here imply a few things – The parentheses denote the use of a function – To use this function, you must provide 2 values • These variables for the function are known as input parameters • In programming, input parameters are more involved which we’ll discuss later • The number of parameters can also vary, some functions take 0, 1, or n number of parameters – In programming, some functions don’t take any at all!

Math Concepts f(x, y) = result • When the function is complete, a resulting

Math Concepts f(x, y) = result • When the function is complete, a resulting value is returned • This value is referred to as the return value • With all 3 parts defined in a math function, we can use the same concepts with programming: – Function name – Input parameters – Return value • Note: for return values, it is important in programming to know what the data type is for the return value (a. k. a. return type)

Code Functions • Here’s a simple program that calculates the area of a rectangle

Code Functions • Here’s a simple program that calculates the area of a rectangle based on user input public static void main(String[] args) { Scanner input = new Scanner(System. in); double length; double width; System. out. print(“Enter length: “); length = input. next. Double(); System. out. print(“Enter width: “); width = input. next. Double(); double area = length * width; System. out. printf(“Area is %. 2 fn”, area); }

Code Functions • There is not much fancy going on in this program –

Code Functions • There is not much fancy going on in this program – read 2 doubles from the user and use those values to calculate the area • The main thing to notice here is that the action of calculating an area may be something that is common – i. e. can be potentially reused • Such actions (a. k. a. “methods”) are useful to separate for reuse by other parts of the program • In this example, only one line of code is representing performing an action of calculating an area • Later, we’ll have actions that will require multiple lines of code so look at this approach as identifying potentially reusable actions (as opposed to using functions to “make things simpler”)

Code Functions • The line that we want to replace then is: double area

Code Functions • The line that we want to replace then is: double area = length * width; System. out. printf(“Area is %. 2 fn”, area); } • We can move this to a separate function as follows: public static double calculate. Area(double l, double w) { double area = l * w; return area; }

Code Functions public static double calculate. Area(double l, double w) { double area =

Code Functions public static double calculate. Area(double l, double w) { double area = l * w; return area; } public static void main(String[] args) { … • First, note that the function is written outside of main and starts with “public static”. This is required for these types of functions – The exact meaning use for static functions is for a later time • Note also that these functions are in the same class where your main function and are at the same level of indentation

Code Functions public static double calculate. Area(double l, double w) { double area =

Code Functions public static double calculate. Area(double l, double w) { double area = l * w; return area; } • “calculate. Area” is the name of the function • Notice we start it with a lower case letter – that is typical Java notation • Note that function names are case sensitive (Calculate. Area is a different function name than calculate. Area) • Subsequent words in the function name start with a capital letter – underscores are okay too • Because functions are performing actions, function names usually start with an action word (e. g. “calculate” and “print”)

Code Functions public static double calculate. Area(double l, double w) { double area =

Code Functions public static double calculate. Area(double l, double w) { double area = l * w; return area; } • “double l” and “double w” in parentheses are the input parameters to the calculate. Area function • Note that l and w are essentially variable declarations with a few added rules: – l and w will be initialized with the values that are coming in when the function is called. – l and w are declared with data types which means the calling function must provide values that match types – The order of l and w matters (first value when the function is called will go to l and the second to w) – When the function ends, l and w will disappear (the scope of the input parameter variables is limited)

Code Functions public static double calculate. Area(double l, double w) { double area =

Code Functions public static double calculate. Area(double l, double w) { double area = l * w; return area; } • The “double” here is the return type • This represents the type of the value that will be returned by the function (i. e. it tells the function caller what type of information to expect when the function is complete) • The “return” statement is the point where the function code officially ends and the value after is what returns to the function caller • The type of the value being returned must match the return type of the function – any code that appears after it will not be reached

Code Functions • With the calculate. Area function available, we now call it from

Code Functions • With the calculate. Area function available, we now call it from main: public static void main(String[] args) { … double area = calculate. Area(length, width); System. out. printf(“Area is %. 2 fn”, area); } • The sequence of actions and variable creations is important to understand • “calculate. Area(length, width); ” means look for a function created that is named calculate. Area and expects to receive two doubles as input parameters

Code Functions • The input parameters in the function call must match the types

Code Functions • The input parameters in the function call must match the types of the function: public static void main(String[] args) { … double area = calculate. Area(“length”, width); System. out. printf(“Area is %. 2 fn”, area); } • This would not call the function we wrote because this is saying call a function called calculate. Area that receives a String and a double as input parameters

Code Functions • The function name must also match exactly: public static void main(String[]

Code Functions • The function name must also match exactly: public static void main(String[] args) { … double area = Calculate. Area(length, width); System. out. printf(“Area is %. 2 fn”, area); } • Even though the input parameter types match, this would not call the function we wrote because this is saying call a function called Calculate. Area (ours is calculate. Area) • When all is correct, the values that are in length and width go to the function – the main function now pauses and control goes to the function

Code Functions • Let’s assume length and width had values 3. 0 and 2.

Code Functions • Let’s assume length and width had values 3. 0 and 2. 1 respectively public static double calculate. Area(double l, double w) { double area = l * w; return area; } • l is now created in calculate. Area and initialized with 3. 0. w will have 2. 1 • Note that main still exists as well as its variables • Its sequence of code is suspended exactly at the point where the function call was made • Control will resume with main after calculate. Area is complete – for now, we’re in calculate. Area’s world

Code Functions public static double calculate. Area(double l, double w) { double area =

Code Functions public static double calculate. Area(double l, double w) { double area = l * w; return area; } • Inside calculate. Area, we execute code as normal • area is declared and initialized with the values of l multiplied by w – in this case, a result of 6. 3 • Note that area is a variable local to the calculate. Area function – just like l and w, when the function ends, area will also disappear

Code Functions public static double calculate. Area(double l, double w) { double area =

Code Functions public static double calculate. Area(double l, double w) { double area = l * w; return area; } • The return statement means the end of the function and the value there is sent back • What happens next is as follows: – The value of 6. 3 that is in area now represents the return value of the function call – l, w, and area all disappear – Control resumes with main and resumes at the exact point where the function call was made – At that exact point, the function call is replaced with the return value

Code Functions public static void main(String[] args) { … double area = 6. 3;

Code Functions public static void main(String[] args) { … double area = 6. 3; System. out. printf(“Area is %. 2 fn”, area); } • The function call is now replaced with the return value and the rest of the line of code is executed – in this case, assigns 6. 3 to the variable “area” • main never knew variables l, w, and area existed and vice versa (calculate. Area never knew length and width existed) • Note both main and calculate. Area both have their own declaration of the variable area – this is okay because their scope is localized to the function they were each declared in • This sequence of function calls is handled in a structure called the “function call stack”

Function call stack • When main starts, the context we are in is main

Function call stack • When main starts, the context we are in is main and all variables in it are created in that world • All variables in main are now actively used main input = (scanner object) length = 3. 0 width = 2. 1 area = ?

Function call stack • When calculate. Area starts, the context changes and all variables

Function call stack • When calculate. Area starts, the context changes and all variables in it are the only ones active • main’s variables are not in context and are essentially temporarily non-existent calculate. Area l = 3. 0 w = 2. 1 main input = (scanner object) length = 3. 0 width = 2. 1 area = ?

Function call stack • When calculate. Area ends, the value in area is what

Function call stack • When calculate. Area ends, the value in area is what is prepped to be returned calculate. Area l = 3. 0 w = 2. 1 area = 6. 3 main input = (scanner object) length = 3. 0 width = 2. 1 area = ?

Function call stack • We return to main because it is the next function

Function call stack • We return to main because it is the next function context on “top” of the stack • The return value of 6. 3 from calculate. Area goes to main’s area variable main input = (scanner object) length = 3. 0 width = 2. 1 area = 6. 3

Function Signatures • Setting up functions like this enables opportunities to reuse code as

Function Signatures • Setting up functions like this enables opportunities to reuse code as needed • Communication between functions is rooted with the function call – this is where the knowing how the 3 parts of a function works is critical • All functions will have a function name, input parameter specification and a return type • These 3 elements make up what is referred to as a “function signature” • Reusing code this way is communicated to other programmers through the function signature often documented in an “Application Programmer’s Interface” (a. k. a. API) • Writing your own and reusing other functions is the heart of the next level of programming

Other Function Notes • Not all functions have return values public static void println(String

Other Function Notes • Not all functions have return values public static void println(String t) • This signature means the function name is “println” that takes a String as an input parameter • Since the return type is “void”, this means when the function ends, no return value is expected • Not all functions have input parameters too public static boolean connect. Database() • This means the function name is “connect. Database” with no input parameters needed and returns a boolean value

Function Summary • Functions help set up code for reuse and also make the

Function Summary • Functions help set up code for reuse and also make the code more readable • When designing overall solutions, creating functions are good areas to act as placeholders for writing code incrementally • Good practice is to find existing code and find areas that can be replaced with functions • More advanced use of functions will be discussed next – become familiar with reading/writing function signatures and using functions accordingly

Programming Exercise 5 • Write a program that tells the user the prime numbers

Programming Exercise 5 • Write a program that tells the user the prime numbers between 2 and a number given by the user • A prime number is a number that is only divisible by itself and the number 1 • First, start the program by asking the user what number to search up to • Then, based on that user number, the program checks each number from 2 to that number and prints all the prime numbers • For example, if the user enters 30, the prime numbers printed on the screen should be 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29

Programming Exercise 5 Programming requirements • You must use a loop to go through

Programming Exercise 5 Programming requirements • You must use a loop to go through all the numbers from 2 to the user number • You must write an “is. Prime” function such that its signature is: – Return type is boolean – Function name is is. Prime – One input parameter that takes an int • You can assume the user will enter a positive number greater than 2 (i. e. no need to do any error checking)

Advanced Control Structures • Now that we have reviewed the fundamentals of selection (if…else)

Advanced Control Structures • Now that we have reviewed the fundamentals of selection (if…else) and repetition programming structures (loops), we can explore some advanced programming capabilities within them • We’ll look at more ways to control a basic loop • We’ll then look at ways to code specific types of multiple if…else selection structures • In the Java online text, this covers us through most of chapter 3 up to and including section 3. 6

Break and Continue • Sometimes it is necessary to end a loop completely while

Break and Continue • Sometimes it is necessary to end a loop completely while going through an iteration • Here’s a variation of the average calculation loop boolean keep. Going = true; double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (keep. Going) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) keep. Going = false; else { total += number; counter++; } } System. out. printf(“Average is %. 2 fn”, total / counter);

Break and Continue • Notice the use of the boolean variable “keep. Going” •

Break and Continue • Notice the use of the boolean variable “keep. Going” • On the first line, we are treating keep. Going like any other variable • Since keep. Going is a boolean, it can only have a value of true or false • In the while loop condition, notice we do not test if it is equal to anything (such as “keep. Going == true”) • This is not necessary because the requirement for the test condition is that it be a boolean value • Since keep. Going already is a Boolean, we can just use its value straight up • This style is often viewed as improved readability of code boolean keep. Going = true; double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (keep. Going)

Break and Continue • Notice also the use of System. out. print • This

Break and Continue • Notice also the use of System. out. print • This is like println except it does not go to the next line after the String is printed on the screen • This is for presentation style and can be used as you prefer with other println and printf code • The effect here is that the cursor appears on the same line as the prompt • When the user enters their data, they will complete it by hitting Enter which, in effect, puts the cursor on the next line while (keep. Going) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double();

Break and Continue • The if statement in the loop body is what controls

Break and Continue • The if statement in the loop body is what controls the loop • If the user enters 0 for their number, the keep. Going boolean variable is set to false and nothing else occurs in the loop • When keep. Going is re-evaluated, since its value is false, the loop ends while (keep. Going) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) keep. Going = false; else {

Break and Continue • In this example, the if statement in the loop body

Break and Continue • In this example, the if statement in the loop body is really controlling the repetition • In such cases, it can be useful to use a “break” statement instead • The following code has the same effect as the previous code example - note the differences double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (true) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) break; total += number; counter++; } System. out. printf(“Average is %. 2 fn”, total / counter);

Break and Continue • The “keep. Going” variable is now gone and the loop

Break and Continue • The “keep. Going” variable is now gone and the loop condition is fixed to a value of true • This means every time the while condition is evaluated, it will always see true and keep doing the loop body • This appears to be an infinite loop, but the if statement takes care of that • When the user enters 0, the if condition will evaluate true • The “break” means to exit the body of code the statement is in – since the break is part of the if statement, the body of code that will be exited is the while loop body • Here, the break effectively ends the loop double total = 0. 0; int counter = 0; Scanner input = new Scanner(System. in); while (true) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) break;

Break and Continue • Notice also that there is no else clause for the

Break and Continue • Notice also that there is no else clause for the if • Technically, this means no matter whether or not the if condition resolves true or false, the code after it executes as normal sequence • In this case, though, when the if resolves to true, the break is executed which effectively ends the loop (making the rest of the loop body code not execute) • The code indirectly acts as an else and is a code pattern that comes up often while (true) { System. out. print(“Enter number or 0 to stop: “); double number = input. next. Double(); if (number == 0) break; total += number; counter++; }

Break and Continue • Another form of loop management variation is “continue” for (int

Break and Continue • Another form of loop management variation is “continue” for (int c = 1; c <= 25; c++) { if (c % 3 != 0) continue; System. out. printf (“Number divisible by 3: %dn”, c); } • In this simple example, the for loop counts from 1 to 25 • For each number, it checks to see if it is divisible by 3 and if so, prints it out • However, the loop body code is written differently – If the number is not divisible by 3, continue the loop – Otherwise print out that the number is divisible by 3

Break and Continue • “continue; ” is the same as break in that when

Break and Continue • “continue; ” is the same as break in that when it is reached, it stops the remaining part of the body of code from executing • Unlike break, continue must be used in a loop body (break can be used in other code bodies as we will see later) • Continue also doesn’t exit the loop – instead, it goes to the evaluation step of the loop and retests – In the for loop example, c++ is also performed • Thus, it is possible with the use of continue to keep the loop going • This is useful in loop designs where the entire loop body does not necessarily have to be executed each time

Switch • Observe the following code: Scanner input = new Scanner(System. in); System. out.

Switch • Observe the following code: Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice = input. next. Int(); if (choice == 1) // Execute code for choice 1 else if (choice == 2) // Execute code for choice 2 else if (choice == 3) // Execute code for choice 3 else // Execute code for all other choice values • This is a straightforward selection statement based on the choice value entered by the user • Logically, this is correct usage of if…else • There are patterns in the code here that commonly occur in programs for which Java provides an alternate form of coding style

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice = input. next. Int(); if (choice == 1) // Execute code for choice 1 else if (choice == 2) // Execute code for choice 2 else if (choice == 3) // Execute code for choice 3 else // Execute code for all other choice values • In the selection statement, all possible outcomes are dependent on testing one variable (choice) • With each test of choice, it is compared to a specific value • When these 2 characteristics are true with an if…else statement, a “switch” statement can be used instead

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice

Switch Scanner input = new Scanner(System. in); System. out. print(“Enter choice: “); int choice = input. next. Int(); switch (choice) { case 1: // Execute code for choice 1 break; case 2: // Execute code for choice 2 break; case 3: // Execute code for choice 3 break; default: // Execute code for all other choice values } • The switch statement functions exactly the same as the if…else statement previously coded

Switch int choice = input. next. Int(); switch (choice) • The switch statement contains

Switch int choice = input. next. Int(); switch (choice) • The switch statement contains a block of code that begins executing a sequence of code where the case value equals the switch variable value • You can read this switch as “if choice equals any of the following…” • “choice” must be a variable that is either an int, char, or enumeration (enum we will discuss later) • These data types can only be used with a switch because they tend to be used for testing for specific sets of values • Strings and doubles have a very high amount of variability (“h”, “him”, etc. or 2. 01, 2. 011) • Only 1 variable can be tested with a switch

Switch { case 1: // Execute code for choice 1 break; case 2: //

Switch { case 1: // Execute code for choice 1 break; case 2: // Execute code for choice 2 break; • The individual cases represent code to begin execution when the switch variable equals the case value • “case 1” is equivalent to “if (choice == 1)” • The code for it is executed as normal – note that there are no curly braces for the case • This is important because any case code to execute is not considered to be in a block

Switch { case 1: // Execute code for choice 1 break; case 2: //

Switch { case 1: // Execute code for choice 1 break; case 2: // Execute code for choice 2 break; • For example, let’s say choice’s value was 2 • Case 2 would be the starting point for the code in the switch block • All code from there is executed to the end of the switch block • This is where the “break” statements become important • What would happen if choice was 1 and the case 1 code did not have a break?

Switch { case 1: // Execute code for choice 1 case 2: // Execute

Switch { case 1: // Execute code for choice 1 case 2: // Execute code for choice 2 break; • Because the case represents the starting point of code in a switch block, all code from there must be treated as a sequence within the block • The rest of the case indicators are ignored • Result is the code above in red is all executed for case 1 • As we saw earlier, “break” means to exit the block of code you are in • That rule applies here for switch blocks • Rule of thumb: Put a “break” first with every case

Switch case 3: // Execute code for choice 3 break; default: // Execute code

Switch case 3: // Execute code for choice 3 break; default: // Execute code for all other choice values } • The last “case” is known as the “default” • This is the point within the switch block where the code execution begins after all other cases are checked • It is the equivalent to the “else” clause in an “if…else” statement • Note there is no “break” statement needed at the end of the default case – it is not necessary because if the default is executed, there will be no code to break from after it (i. e. you’re at the end of the switch block)

Switch case 3: case 4: case 5: // Execute code for choices 3, 4,

Switch case 3: case 4: case 5: // Execute code for choices 3, 4, and 5 break; default: // Execute code for all other choice values } • Here, a range of switch values is tested • This is the equivalent of “if (choice == 3 || choice == 4 || choice == 5)” – You can think of it as choice >= 3 and choice <= 5, but case statements are often better to think of as starting points for specific values • If choice is either 3, 4, or 5, the search within the switch would reach one of those case lines and execute code from there as normal

Switch • Switch statements are generally considered to be the preferred style of code

Switch • Switch statements are generally considered to be the preferred style of code when the opportunity is there • The logical equivalent using if…else can always be done instead and ultimately becomes a matter of style • Switch can only be used in situations where you are testing 1 variable for specific values • Typical uses are for handling selections from a menu or performing actions based on different types of data read • If you have a wide range of possible values to consider, it will likely be better to go with an if statement

Programming Exercise 6 • Create a program that simulates rolling a 6 -sided die

Programming Exercise 6 • Create a program that simulates rolling a 6 -sided die 6, 000 times • For each die roll, the result is tracked to keep track of how many times a number occurs • After all the rolls are complete, display the frequencies of each number that came up (i. e. show many times a 1 was rolled, a 2 was rolled, etc. up to 6) • Do not show the result of each roll, only simulate it and record the result – the only thing the user sees is the final report of number frequencies

Programming Exercise 6 Programming requirements • You must use a random number generator as

Programming Exercise 6 Programming requirements • You must use a random number generator as we discussed in class and available in the code supplements to simulate rolling the 6 -sided die • You must use a switch statement to handle capturing the result of rolling the die to keep track of your frequency counts • You do not have to use a function, though it may be useful in some areas • You can hard code the number of times to roll the die, but you can also get the number from the user if you want to practice