Share
Embed
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
59 slides
-
Memory Upload • Arrays and methods • Using the debugger
• Command line arguments • Exceptions • Reading from a file -
Introduction • ICS 211: Introduction to Computer Science II
William Albritton • Leeward Community College • Mathematics and Natural Sciences Division • Information and Computer Sciences Department -
Example Program • On the class website, see the link
to ArraysAndMethods.java • This program shows how to: Return an array from a method Pass an array to a method -
Example Program • You may want to look at this
program while I explain the details of the program in the next few slides -
Why Use Methods? • Using methods in our code is
also a good way to be a lazy programmer Remember: we want the computer (not us!) to do the work • Main advantage of methods Instead of rewriting the same code over and over, we can use just one method over and over -
Three Methods 1. public static void main(String[] args) Main
method starts the program Also calls the next two methods 2. public static String [] createStooges() Creates and returns an array of Strings 3. public static void displayArray (String [] anArray) Displays an array of Strings -
Returning an Array • Syntax for a method call that
returns an array DataType [] arrayName = method(); • Assigns the return value of the method to the array -
Returning an Array • Syntax for a method definition that
returns an array public static ReturnType [] method(){ //method's code return array; } • Be sure to add square brackets after the class name of the return type [ ] -
Returning an Array • Note that arrayName will be assigned
the address of array DataType [] arrayName = method(); -
Array Return Example • This code assigns the address of
array stooges to the array stoogesNames String [] stoogesNames = ArraysAndMethods.createStooges(); Method call is in the main() method • The method createStooges() is a static method, so method call uses syntax: ClassName.methodName() -
Array Return Example • This method definition declares, instantiates, initializes,
and returns an array of Strings public static String [] createStooges(){ String [] stooges = new String[3]; stooges[0] = new String("Larry"); stooges[1] = new String("Curley"); stooges[2] = new String("Moe"); return stooges; } -
Array Return Example public static String [] createStooges(){ String []
stooges = new String[3]; stooges[0] = new String("Larry"); stooges[1] = new String("Curley"); stooges[2] = new String("Moe"); return stooges; } This method definition is below the main() method -
Call vs. Definition • A functional comparison A method
call tells the corresponding method definition to execute the code contained within that method definition A method definition contains a block of code that has a specific task -
Call vs. Definition • A physical comparison The code
for a method call is placed inside a method definition (inside the curly brackets) The code for a method definition is placed inside the class definition (inside the curly brackets) {…} -
jGRASP Tip • Press the Generate CSD (Control Structure Diagram)
button to match indent the nested curly brackets • This button is on the top, towards the left, & looks similar to the icon below -
Parameters • Parameters are a way to send data from
a method call to a method definition • This makes our methods more flexible, as we can input different kinds of data to the method -
Array Parameters • Syntax for a method call that passes
an array as the actual parameter method(arrayName); Just use the name of the array Do NOT use the square brackets!! -
Array Parameters • Syntax for a method definition that passes
an array as the formal parameter public static ReturnType method(DataType [] parameter){ ... } -
Array Parameters Add square brackets after data type of
formal parameter -
Array Parameters • Variables arrayName & parameter point to (reference)
the same array • Method call method(arrayName); • Method definition public static ReturnType method(DataType [] parameter){ ... -
Array Parameters Example • Method call is in the main()
method ArraysAndMethods.displayArray (stoogesNames); • Method declaration is below the main() method public static void displayArray(String [] anArray){ //code to display an array } -
Debugger • A debugger is a tool that allows you
to run your program step by step, one line of code at a time Also displays the value for each variable • Useful not only for finding bugs, but also understanding how methods work -
Debugger Instructions 1. Compile the program by pressing the green
plus button 2. Set a breakpoint by moving the mouse to the left side of the screen and clicking the left mouse button A red dot will remain on the screen -
Debugger Instructions 1. Compile the program by pressing the green
plus button 2. Set a breakpoint by moving the mouse to the left side of the screen and clicking the left mouse button The breakpoint is where the debugger will start The breakpoint must be on a line that has executable code -
Debugger Instructions 3. Run the debugger by pressing the ladybug
button 4. On the far left, a Debug window will appear • This has a list of the variables and their corresponding values -
Debugger Instructions 3. On the top left of the Debug
window, press the Arrow that Curves Right This will step into each method -
Command Line • Programs can be run on UH UNIX
using the command line interface The command line is the line at the prompt on the UNIX shell • Commands Text editor: emacs Program.java Compiler: javac Program.java Interpreter: java Program -
UNIX & Emacs • For more information on using the
UNIX shell and Emacs, see the links on the ICS 211 class web site • You are welcome to use any programming environment to edit, compile, and run your programs • For example, you could use Pico, Vi, Eclipse, etc. -
What is “args”? • What is “args” that we always
type in the main() method? public static void main(String [] args) • The args (arguments) variable is a parameter and an array of Strings • args is used to access the command line arguments -
Example Program • Below is I/O for program Repeat.java javac
Repeat.java java Repeat one two three args[0] = "one" args[1] = "two" args[2] = "three" -
Command Line & jGRASP • To use command line arguments
in your program on jGRASP 1.On the top menu, click Build 2.On the drop-down menu, click Run Arguments 3.A Run Arguments text field will appear at the top of the screen 4.Type your command line arguments into this text field -
Exceptions • An exception is a runtime event that is
an error Runtime means “during program execution” or “the time when the program is running” -
Exceptions • Used by a program in two ways 1.
Throws (raises, creates) an exception to indicate that an exception has occurred 2. Catches (lowers, ends) an exception, so that code can be executed that handles (deals with) the error in some way -
Example Exceptions • Division by zero Integer result = 7
/ 0; Throws ArithmeticException -
Example Exceptions • Incorrect index for an array Integer []
numbers = {10, 20, 30, 40, 50}; Integer lastNumber = numbers[5]; Throws ArrayIndexOutOfBoundsException -
Try Block • A try block is a section of
code containing statements which might throw an exception A block is the code contained between curly brackets try{ statement1; statement2; statementN; } -
Try Block Execution • Code within the try block will
execute until an exception is thrown Any code located below the exception will not execute try{ statement1; statement2; statementN; } -
Catch Block • A catch block is a section of
code which will handle a particular exception catch(ExceptionClass variable){ statement1; statement2; statementN; } -
Catch Block Execution • Code within the catch block will
execute only if an exception is thrown which is an object of the same class as the parameter class -
Try-Catch Block Syntax • One try block is immediately followed
by one or more catch blocks try{ statement(s); } catch(ExceptionClass1 variable1){ statement(s); } catch(ExceptionClassN variableN){ statement(s); } -
Try-Catch Block Execution • If an exception is thrown in
a try block, program control skips over remaining statements in the try block, & continues in the catch block which corresponds to the exception’s type • If an exception is not thrown, then program control continues after the last catch block -
Try-Catch Block Execution • Once control comes to end of
catch block, program control continues after the last catch block • If the program has no matching catch blocks, the program crashes -
Try-Catch Block Example • See program TryCatchBlocks.java try{ Integer result
= 7 / 0; Integer [] numbers = {10, 20, 30, 40, 50}; Integer lastNumber = numbers[5]; } catch(ArithmeticException e1){ System.out.println("Division error"); } catch(ArrayIndexOutOfBoundsException e2){ System.out.println("Array error"); } -
Programming Tip • Initialize all of your variables for each
method at the top of each method • This way, you do not have to worry about scope issues Scope is where a variable is visible (where it can be used in a program) • See program TryCatchBlocks.java for an example (at top of main method) -
Types of Exceptions • Like other classes, exceptions have a
class hierarchy See the link to the Java API on the class webpage and find the Exception class • Exceptions can be broken down into two main types 1. Runtime (unchecked) exceptions 2. Checked exceptions -
Runtime Exceptions • A type of exception that does not
require a try-catch block Usually can be prevented by careful programming Not considered a serious error -
Runtime Exceptions • A type of exception that does not
require a try-catch block Subclasses of RuntimeException 1. ArithmeticException 2. NullPointerException 3. ArrayIndexOutOfBoundsException 4. StringIndexOutOfBoundsException -
Checked Exceptions • A type of exception that must be
placed in a try-catch block Signify that a “serious problem” has occurred Subclasses of Exception 1. FileNotFoundException 2. IOException -
Reading from a File • Need these import statements at
top of your program import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; -
Reading from a File • Next we need a File
constructor File file = new File("fileName"); Where "fileName" is a String object with the name of the file • The File constructor does not create a new file The File constructor only connects our program to an existing file -
Reading from a File • The File constructor needs a
string that is either: Simply the name of the file if the file is in the current directory "file2.txt" Or full name of path to the file "C:\ics211\array\file2.txt" -
Reading from a File • Scanner’s constructor needs a File
object and a try-catch block File file = new File("file2.txt"); Scanner scanner = null; try{ scanner = new Scanner(file); } catch(FileNotFoundException e){ System.out.println("No file!");); } -
Reading from a File • Must have a try-catch block,
as the program will throw a checked exception if the file cannot be found -
Example Program • See ReadFromFile.java Reads from a file,
which has the same name as the 1st command-line argument (commandlineArguments[0]) If file does not exists, with throw FileNotFoundException and end Scanner method hasNextLine() will return “true” if more lines are in the file, otherwise “false” -
Memory Defragmenter • Using arrays with methods • Debugger instructions
• Command line arguments (args!) • Try-catch blocks and exceptions • Read from a file -
Task Manager • Before the next class, you need to:
1.Do the assignment corresponding to this lecture 2.Email me any questions you may have about the material 3.Turn in the assignment before the next lecture 4.Get out and enjoy a nearby beach!