Upgrade to Pro — share decks privately, control downloads, hide ads and more …

lecture03.pdf

Avatar for William Albritton William Albritton
August 13, 2014
140

 lecture03.pdf

Avatar for William Albritton

William Albritton

August 13, 2014
Tweet

Transcript

  1. Memory Upload • Arrays and methods • Using the debugger

    • Command line arguments • Exceptions • Reading from a file
  2. Introduction • ICS 211: Introduction to Computer Science II 

    William Albritton • Leeward Community College • Mathematics and Natural Sciences Division • Information and Computer Sciences Department
  3. 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
  4. Example Program • You may want to look at this

    program while I explain the details of the program in the next few slides
  5. 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
  6. 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
  7. 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
  8. 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 [ ]
  9. Returning an Array • Note that arrayName will be assigned

    the address of array DataType [] arrayName = method();
  10. 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()
  11. 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; }
  12. 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
  13. 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
  14. 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) {…}
  15. 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
  16. 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
  17. 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!!
  18. Array Parameters • Syntax for a method definition that passes

    an array as the formal parameter public static ReturnType method(DataType [] parameter){ ... }
  19. Array Parameters • Variables arrayName & parameter point to (reference)

    the same array • Method call method(arrayName); • Method definition public static ReturnType method(DataType [] parameter){ ...
  20. 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 }
  21. 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
  22. 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
  23. 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
  24. 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
  25. Debugger Instructions 3. On the top left of the Debug

    window, press the Arrow that Curves Right  This will step into each method
  26. 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
  27. 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.
  28. 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
  29. 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"
  30. 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
  31. Exceptions • An exception is a runtime event that is

    an error  Runtime means “during program execution” or “the time when the program is running”
  32. 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
  33. Example Exceptions • Incorrect index for an array Integer []

    numbers = {10, 20, 30, 40, 50}; Integer lastNumber = numbers[5];  Throws ArrayIndexOutOfBoundsException
  34. 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; }
  35. 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; }
  36. Catch Block • A catch block is a section of

    code which will handle a particular exception catch(ExceptionClass variable){ statement1; statement2; statementN; }
  37. 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
  38. 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); }
  39. 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
  40. 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
  41. 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"); }
  42. 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)
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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;
  48. 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
  49. 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"
  50. 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!");); }
  51. Reading from a File • Must have a try-catch block,

    as the program will throw a checked exception if the file cannot be found
  52. 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”
  53. Memory Defragmenter • Using arrays with methods • Debugger instructions

    • Command line arguments (args!) • Try-catch blocks and exceptions • Read from a file
  54. 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!