310 likes | 437 Vues
This lecture focuses on functions in Java, using a relatable wake-up routine as an example. It introduces key concepts such as function definition, modifiers, and void return types. The session explores the construction of simple functions such as `printPhraseCharacters` and `areaOfCircle`, demonstrating how to define and call functions. Additionally, we cover nested loops and arrays in the context of performing an insertion sort. By the end of this lecture, you'll have a clearer understanding of how to create and use functions effectively in Java programming.
E N D
COP3502: Introduction to CIS I Lecture 7
public class wakeUp { public static voidmain(Stringargs[]) { getOutOfBed(); brushTeeth(); takeShower(); makeCoffee(); eatBreakfast(); } }
“void” functions <modifiers> void<function name> ( <arg type> <arg name> , …) { <function body> } public static voidprintPhraseCharacters(Stringphrase) { char characters[] = phrase.toCharArray(); for (inti = 0; i < characters.length; i++) { System.out.println(characters[i]); } }
function call public class printTest { public static voidmain(Stringargs[]) { StringmyName = “Sean”; printPhraseCharacters(myName); } }
public class printTest { public static voidmain(Stringargs[]) { ….. } public static voidprintPhraseCharacters(String phrase) { ….. } }
functions w/ return values <modifiers> <return type> <function name> ( <arg type> <arg name> , …) { <function body> } public static doubleareaOfCircle(doubleradius) { double area = Math.PI * (radius * radius); return area; }
return keyword returnexpression; return x; return x + 5; returnrandomNumber();
function call public class printTest { public static voidmain(Stringargs[]) { double radius = 5.2; double area = areaOfCircle(radius); } }
arrays … 9 0 1 2 3 4 7 8 5 6
int[] list = {8, 4, 1, 7, 3, 2} int list[] = {8, 4, 1, 7, 3, 2} 0 1 2 3 4 5
insertion sort build sorted list one element at a time
insertion sort build sorted list one element at a time
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }
insertion sort if (red < green arrow) { SWAP }