Title: CISC 101 Week 3
1CISC 101 Week 3
- Building Programs defining our own methods
- Building Data Structures 1D arrays
- Using Files for reading input saving output
2Overview Week 3 Topics
- 1. program development
- defining new methods
- 2. data structures
- introduction to arrays
- 3. file Input/Output
- reading input from files, writing output to files
3Defining New Methods
- Why learn about defining methods?
- we write new methods for subtasks of programs
- as we develop the algorithm for a program
- we specify the major separate steps in the
solution - we then code each major step as a new method
- this approach allows modularity
- modules that are methods
- can be independently developed tested
- these smaller modules are more easily maintained
- methods that implement subtasks are often
re-usable
4Defining New Methods
- What is a method definition?
- a method consists of
- 1. a header line
- and
- 2. a body of Java instructions
- the header line names describes the method
- a method may include its own local data
- a method is called by name anywhere in the
program - the body of the method
- is a compound statement, a block
- the Java instructions that do the work in the
subtask
5Defining New Methods
- How do we use the methods we define?
- with methods for subtasks our programs become
- collections of method definitions
- any method may use or call any other
- the main method
- often consists mostly of a list of calls to other
methods - methods we define
- implement the subtasks of the algorithm
6Sample Method Definitions
- public class MyAP //class header line
-
- // header returns int, int parameter
- public static int absVal (int num)
- // body compound statement
- if (num gt 0)
- return num
- else // return statements
- return -num
-
- // header no return value, no parameters
- public static void printMsg ( )
-
- System.out.println("Welcome to my
program!") -
- // header no return value, 1 parameter
- public static void main (String args)
7Sample Method Definitions
- // other methods you could include use in
any program - public static void pauser ( )
-
- System.out.print ("Press \"ENTER\" to
continue") - String junk TextFile.KEYBOARD.readLine (
) -
- public static void putLines (int num)
-
- int i 0
- while (i lt num)
-
- System.out.println ( )
- i i 1
-
-
- public static int intPower (int base, int
exponent) -
8Sample Method Definitions
- calling the newly defined methods
- // the main method can be short clear
- // it consists mostly of calling the newly
defined methods - public static void main (String args)
-
- System.out.println("Program execution
begins") - pauser( )
- System.out.print("The fifth power of 2 is"
intPower(2, 5)) - putLines(2)
- System.out.print("The fifth power of 3 is"
intPower(3, 5)) - pauser( )
- System.out.println("Normal program
termination, goodbye") - // end main
- // end class
9Method Definitions Analysis
- method definition syntax
- public static type methodName (parameterList) //
header line -
- local variable declarations // body in 's
- statements
- return statement
-
- the major parts of a method definition are
- 1. the header line
- it describes names the method
- 2. the body
- a block, a compound statement in 's
- it lists instructions to execute when the method
is called
10Method Definitions Analysis
- public static type methodName (parameterList) //
header line - details of the method header line
- public static are Java keywords
- all our method headers can begin with these 2
keywords - type
- here, the word "type" is just a placeholder
- in actual method definitions we fill its place
with either - 1.void
- if the method just executes some instructions
- for example methods that just print output
- 2. the type of the data value the method returns
- when a method returns a value
- it could be any Java type, primitive or
reference/object - int, double, boolean, char, String, ....
11Method Definitions Analysis
- public static type methodName (parameterList) //
header line - method header details
- methodName
- a Java identifier the name we use to call the
method - we should make up a legal identifier that is
descriptive - ( ) parentheses
- are always part of a method definition of a
method call - they may be empty
- their job in the definition
- is to enclose what we call the parameter list
- their job in the call
- is to enclose the arguments corresponding to
parameters - parameters
- are the mechanism to communicate data into the
method
12Method Definitions Analysis
- public static type methodName (parameterList) //
header line - more method header details
- (parameterList)
- a comma separated list of pairs with the form
- type parameterName, type parameterName, ...
- for example (int x, double a, String name)
- they pass input data values to the method
- parameters
- 1. act like variables that are local to the
method - 2. are matched to argument list elements at
method call - 3. get their initial values when the method is
called - How? the system assigns an argument value
- to the matching parameter parameter argument
value
13Method Definitions Analysis
- more method header details
- (parameterList)
- // recall the header for the intPower method
- // public static int intPower (int base, int
exponent) - // here's an example call of
- // intPower in a main method
- int a 10, b 4, x
- x intPower(a, b)
- What happens at method call?
- base a
- exponent b
- then the system executes the body of the method
- with base having the value of a
- exponent having the value of b
14Method Definitions Analysis
- method body details
- the body is a compound statement or block
- the instructions to execute when the method is
called - it is enclosed in braces
- public static void putLines (int num) // header
line -
- int i 0
- while (i lt num)
-
- System.out.println ( )
- i i 1
-
15Method Definitions Analysis
- method body details the body includes
- 1.any local variable declarations
- int i 0
- variables needed only while the method executes
- 2. statements
- any Java statements, including
- assignment, selection, repetition, calls of other
methods - these are executed when the method is called
16Method Definitions Analysis
- method body details the body includes
- local variable declarations
- Java statements to execute
- some methods include a return statement
- if method is not void
- there must be at least 1 return statement
- the value of the expression after keyword return
- becomes the result of the method call
- when a return statement is executed
- the method call ends
- even if there are other statements in the body,
after it - the value following the word return "replaces"
the call
17Method Definitions Analysis
- method body details the return statement
- recall the absVal method shown earlier
- // header returns int, int parameter
- public static int absVal (int num)
- // body compound statement
- if (num gt 0)
- return num
- else // return statements
- return -num
-
- a call to this method ends
- when one of the return statements executes
- the method produces a value
- either num or -num
18Method Definitions Summary
- 1. methods
- improve program structure/modularity
- allow independent development testing
- are often re-usable in other programs
- 2. parameters
- communicate data into the method
- declared in a list of type name pairs in the
header - allow different behaviour on different calls
- are local to the method
- are accessed by name within the method
- get initial values from corresponding arguments
19Method Definitions Summary
- 3. the return statement
- allows a method to produce a single value
- the return value type
- is specified by a type name in the method header
- public static int intPower (int base, int
exponent) - if the method header specifies a type
- there must be a return statement in the
definition body - the method ends when a return statement executes
- return pow
- methods returning results are used as values
- typically they are used in expressions
- generally they are not used as stand-alone
statements - x intPower(a, b) // a call to intPower
produces a value
20Data Structures 1D Arrays
- What is the reason for arrays?
- we can combine multiple data items of same type
- and refer to them using one name
- they give us a way to represent lists of values
- many problems involve lists of data
- examples
- the measurements from 10 trials in an experiment
- a student's grade in each of 11 quizzes
21Data Structures 1D Arrays
- What are arrays?
- an array is a form of data structure
- it is a numbered list of data elements
- in Java, array types are specified by brackets
- the general form for an array type is typeName
- array types are reference, or class types
- an array variable refers to an array object
22Data Structures 1D Arrays
- How do we create and use arrays?
- declaring an array variable creating a new
array - double exptData new double 10
- the number inside the blue brackets
- specifies the number of data elements in the
array - when we create an array in Java, we specify its
size - to access one element of an array, we use
- the name an index number or variable in
brackets - like this exptData i
- the legal values of i are 0 lt i lt 9
23Data Structures 1D Arrays
- declaring array variables creating arrays
24Data Structures 1D Arrays
- Java arrays are objects
- each array has an attribute called length
- we can access it using the array name length
- for the example exptData.length
- for exptData, the length attribute has the value
10 - unlike most Java objects, arrays have no methods
- some array terminology
- the base type the type of each element of the
array - the length or size the number of elements in the
array - an index or subscript a number specifying one
element - the array bounds the min max values for the
index
25Data Structures 1D Arrays
- using array elements
- in your program, you may use an array element
- wherever you could use
- one value or variable of the base type
- for example, exptData2 stores a double value
- can be used wherever a double value or variable
can - // retrieving storing array element values
- double product exptData0 exptData9
- exptData3 product
261D Array Summary
- 1D Java arrays
- group data items of the same type into a list
- each list item has a position number (index or
subscript) - the declaration syntax is
- typeName variableName new typeName
numElements - int nums new int 5
- the semantics, or meaning of this statement is
- 1. declare a new variable nums
- its type is int , or array of ints
- 2. create a new array object
- the new array can hold 5 int values
- the variable nums refers to the new array object
- the new array object has 1 attribute nums.length
271D Array Basics
- array declaration creation
- here's a pictorial representation of what happens
- int nums new int 5
281D Array Basics
- 0-based indexing
- why is the first element arrayName0?
- for most of us, counting numbers start at 1, not
0 - reason is technical related to memory addresses
- an array variable refers to some memory address
A - the start of the part of memory reserved for the
array - each array element uses fixed of memory
locations E - for example, an int value takes 4 bytes of memory
- any given array element
- is some of positions, P, away from A
- to calculate the memory address for any element
- we could use the formula A (P E)
- the first element is zero positions from the
start, A - so it is designated as arrayName 0
291D Array Basics
- 0-based indexing
- why the first element is nums0
- each red square represents 1 byte of memory
- int nums new int 5
301D Array Basics
- more about array declarations
- we can make multiple declarations in 1 statement
- double a new double 5, b new double
10 - at declaration, we can use an array literal
- to create initialize a new array
- braces enclosing list of values separated by
commas - int oddInts 1, 3, 5, 7
311D Array Basics
- accessing using array elements
- access arrayIdentifierlegalIndexValue
- nums3, b8
- recall bounds on legal index values are 0 to
length - 1 - you may use an array element
- wherever you can use 1 value of the base type
- // get the value from location 0 of array b,
assign it to x - double x b0
- // do arithmetic with values stored at 2
locations in nums - int myInt nums2 nums4
- // assign a new value to an array location
- nums3 myInt 5
321D Array Basics
- there is a typical 1D array access pattern
- visit each array location in turn
- set or use the value stored there
- examples array initialization, sum array
elements - initialization is considered good programming
practice - int arr new int 25
- int i 0, sum 0 // i counter or index
variable - while (i lt arr.length)
-
- // use the index variable to access each
location - arri (int)(100 Math.random())
- // increment the index variable for the next
location - i i 1
-
- i 0
- while (i lt arr.length)
331D Array Basics
- 1. constants arrays
- a constant is given a value just once
- is useful for repeatable, maintainable array
sizing - // declare a constant at the beginning of your
program - public static final int MAX 20
- // use it to create a local array in any method
- int arr new int MAX
- 2. when code accesses all array elements
- use the length attribute as the index upper bound
- int i 0
- while (i lt arr.length) // or (i lt arr.length -
1) -
- sum sum arri // access the ith array
element - i i 1 // increment i
341D Array Basics
- array bounds errors are common
- using an illegal index or subscript value
- typically, this is an "off by one" error
- while ( i lt a.length)
-
- System.out.println("Element " i " is"
ai) - i i 1
-
- this code tries to access one too many locations
- it illegally calls for access of location
aa.length - this results in a run-time error
- that causes the program to crash, with an
exception
351D Array Basics
- summary hints
- it is a good habit to initialize your arrays
- use an array literal at declaration
- or, use repetition to access set all elements
- Java arrays are objects
- the array variable refers to the array object
- the array object consists of
- locations for the data, plus the length attribute
- using one array element arrayNameindexValue
- is the same as using 1 value or variable of the
base type
36File I/O
- first, review keyboard input screen output
- for screen output
- we use the Java built-in, System.out, or
TextFile.SCREEN - for keyboard input
- to read data typed into the terminal window by
the user - we use TextFile.KEYBOARD methods
- sometimes we need files for input output
- especially for long-term storage of large
datasets - TextFile supplies the appropriate methods
- to connect external file names to identifiers in
a program - to read from or write to those external files
37Review Screen Output
- screen output (standard output)
- the System class includes an object called out
- it has easy to use print( ) println( ) methods
- System.out.print ( ), System.out.println ( )
- they are void methods (they don't return a result
value) - they are overloaded
- there are multiple methods with the same name
- print println versions for all the primitive
types Strings - recall that String arguments for output
- are often produced by concatenating multiple
values - // example of concatenating values for output
- System.out.println(n1 " " n2 " sums to"
(n1 n2))
38Review Screen Output
- TextFile.java has a SCREEN object
- with print ( ) and println( ) methods
- similar to System.out's print( ) println( )
- for int, char, boolean, double, String types
- TextFile's SCREEN methods have extra versions
- with a 2nd argument for field width
- with a 3rd argument for the number of decimal
places - this 3-argument version is just for doubles
- TextFile.SCREEN.print ("Sometimes TextFile
printing methods") - TextFile.SCREEN.println (" can replace System.out
methods.") - TextFile.SCREEN.print(1.0 / 3.0, 10, 2) // the
call - 0.33 // the output
39Review Keyboard Input
- keyboard input (standard input)
- we use TextFile.java's KEYBOARD object
- its methods read input values from the keyboard
- each method returns the value read in as its
result - there are methods for several primitive data
types - char, int, double
- plus, there are methods for words entire lines
- these are returned as Strings
- // return an int read from keyboard
- int temp TextFile.KEYBOARD.readInt ( )
- // return a whole line of keyboard input as a
String - String nextLine TextFile.KEYBOARD.readLine ( )
40Review Keyboard Input
- TextFile.KEYBOARD's input methods
- readInt( ), readDouble( ), readChar( )
- return an int, a double, a char respectively
- these methods require properly formatted input
- input that isn't a proper literal causes an error
- readWord( ) readLine( )
- each returns a String
- either the next group of whitespace delimited
characters - or, the rest of the current line
41File I/O Introduction
- Why bother with File I/O?
- 1. for large data sets
- are awkward for screen display, for keyboard
typing - 2. for long term storage
- the data persists after the program finishes
running - 3. for repeated access
- keep a data set and use it more than once
- 4. for program to program transfer
- one program runs to produce output data
- that data is used as input for some other program
42File I/O Introduction
- What is file I/O and how do we use it?
- with file I/O
- disk files are the source for program input
- disk files are the destination for program output
- we use TextFile to create a link
- between an identifier in our program
- a file that exists independently of the program
- TextFile input file objects have instance methods
- to read input data, to test for end-of-file, to
close the file - TextFile output file objects have instance
methods - to write output data, to format output, to close
the file
43File I/O For Our Programs
- File I/O is an important reason for TextFile
- standard Java does include file I/O
- but it can be awkward for new programmers
- TextFile.java includes simple file I/O
- so we always include TextFile.java in each BlueJ
project
44File I/O Input
- using TextFile for file input
- this statement
- TextFile inFile new TextFile (TextFile.INPUT,
"fileName") - 1. declares a variable
- 2. connects it to a file object
- the variable inFile is the internal name for a
disk file - the String "fileName" is the external name of the
file - inFile refers to a new file object
- the constructor method connects to opens the
file - to indicate we want to open a file for input
- we use the constant TextFile.INPUT as the first
argument
45File I/O Input
- TextFile file input for our programs
- TextFile inFile new TextFile (TextFile.INPUT,
"fileName") - the second argument is a String naming the file
- the String may be just the file's name
- so long as the file is in the BlueJ project
folder - otherwise, the name must include path information
- the String must name a file that already exists
- if there is not already a file with that name
- it will cause an error program crash
46File I/O Input
47File I/O Input
- TextFile methods for input files
- read return primitive data values Strings
- method names are the same as for
TextFile.KEYBOARD - but we use them with a particular TextFile object
- iFile.readInt( ), iFile.readChar( ),
iFile.readDouble( ) - iFile.readWord( ), iFile.readLine( )
- in addition
- 1. we can test for reaching the end of an input
file - iFile.eof( )
- returns true if we've reached the end of the file
- 2. there are two void methods
- one to skip past whitespace iFile.skipWhiteSpace(
) - one to close a file iFile.close( )
48File I/O Output
- TextFile file output for our programs
- TextFile oFile new TextFile (TextFile.OUTPUT,
"fileName") - declare a variable connect it to a file object
- the oFile variable is the internal name for the
file - the String "fileName" is the external name for
the file - the constructor method connects to opens the
file - when opening a file for output
- use the constant TextFile.OUTPUT as the first
argument - if the named file does not already exist
- the constructor creates it in the current folder
- connects to it opens it for writing
- and what if the named file already exists?
- the constructor connects to it opens it for
writing - whatever we write will overwrite any existing
contents
49File I/O Output
- TextFile instance methods
- these are void methods for writing output values
- the same method names as for TextFile.SCREEN
- but we use them with a particular file object
- oFile.print( ) oFile.println( )
- as with TextFile.SCREEN, there are additional
versions - with a 2nd argument to specify field width
- for double values there can be a 3rd argument
- to specify precision (the number of decimal
places) - plus there is a void method for closing the file
- oFile.close( )
50File I/O
- file I/O notes
- the usual identifier rules apply to file
variables - creating a file object
- associates a program variable with an external
file - the variable declaration initialization
- may be separate statements
- you may mix file I/O with screen keyboard I/O
- see the example on the next slide
- note that you can't mix
- reading from writing to the same file
- at a given time, it can only be open for one or
the other
51File I/O
- a file example
- mixing screen, keyboard file I/O
- // separate declaration initialization
- // of primitive file variables
- int someNum
- someNum -5
- TextFile oFile
- // a common programming strategy user supplies
the file name - System.out.print ("Enter the name of the output
file") - String fName TextFile.KEYBOARD.readLine( )
- // now open the file for writing, write to it,
close it - oFile new TextFile(TextFile.OUTPUT, fName)
- oFile.println(someNum)
- oFile.close( )
52File I/O
- another partial example
- // variables for files user supplied names
- TextFile inFile, outFile
- String inFileName, outFileName
- // get input file name from user
- System.out.print("Enter the name of the input
data file ") - inFileName TextFile.KEYBOARD.readLine( )
- inFile new TextFile(TextFile.INPUT,
inFileName) - // get output file name
- System.out.print("Enter the name for the output
file") - outFileName TextFile.KEYBOARD.readLine( )
- outFile new TextFile(TextFile.OUTPUT,
outFileName) - while (!inFile.eof())
-
- outFile.println(inFile.readLine())
53File Output Some Details
- file output methods
- oFile.print( ), oFile.println( )
- are void methods of file objects
- each adds text to the output file
- basic output
- uses the single parameter versions
- oFile.print(dataVal) oFile.println(dataVal)
- each is overloaded
- there are multiple versions for different data
types - boolean, char, int, double, String
- the argument is added to the output file
- with or without going to the beginning of a new
line
54File Output Some Details
- formatting output for files
- we use the 2 3 parameter versions
- of the print ( ) println ( ) methods
- just like the TextFile.SCREEN output methods
- oFile.print(someArg, fieldSize)
- someArg may be an int, a double or a String
- fieldSize is a positive int
- oFile.print(num, fieldSize, decimalPlaces)
- num is a double value or variable
- fieldSize decimalPlaces are positive ints
55File I/O Review
- input reading methods
- these are instance methods with no parameters
- each method returns a value, the value read
- iFile.readInt( ), iFile.readDouble( ),
inFile.readChar( ) - iFile.readLine( ), iFile.readWord( )
- output writing methods
- these are void instance methods
- with one, two or three parameters
- oFile.print(val) oFile.println(val)
- each converts ( possibly formats) the argument
- then adds it to the output file
56File I/O Special Methods
- special input methods
- a void method to "consume" whitespace
- iFile.skipWhiteSpace( )
- a boolean method
- to test for reaching the end of the file
- iFile.eof ( )
- String data
- while (!iFile.eof( ))
-
- data iFile.readLine( )
- oFile.println(data)
57File I/O Special Methods
- special input output methods file closing
- It's good programming practice to close files as
soon as read/write operations are done. - We use void instance methods with no parameters.
- TextFile iFile new TextFile(TextFile.INPUT,
"inName.txt") - TextFile oFile new TextFile(TextFile.OUTPUT,
"outName.txt") - String data
- while (!iFile.eof( ))
-
- data iFile.readLine( )
- oFile.println(data)
-
- iFile.close( )
- oFile.close( )