Title: COMP 14 Introduction to Programming
1COMP 14Introduction to Programming
- Classes and Arrays
- Monday, July 17, 2006
2Today
- Assignment 4
- Assignment 5
- Finish up Chapter 8
- toString
- Finalizers
- More on classes
- Examples
- Packages
- Chapter 9 Arrays
- Declare
- Instantiate
- Initialize / Set values
- Step through every element of an array
3Assignment 4
- Most-common problems
- Not following directions
- Some of you did not do the design document
- The point of the design document was to make it
easier on you - If you wrote most of the design document after
writing the code then it was more work - Losing a lot of points on the simplest parts
- File Headers in all .java files
- (template available from class website)
- Lessons Learned
- Think and design before coding
- Start implementing a small part before trying to
get the entire thing working - Example solution
- TicTacToeBoard1.java
- Questions?
4Improving Assignment 4
- How could we have better created the tic-tac-toe
program using the concepts we have recently
learned? - TicTacToe.java
- Written by Josh Lockhart
- Uses methods to break the problem down into
easier to write/understand sub-problems - Also notice the header/comments and use of
whitespace (i.e., indentations and newlines)
5Assignment 5
- Submit everything as a .jar file
- Puts all files into a single file
- Include java files and write up
- Demo of how to do this in jGRASP
- Extra day
- Since I am returning and reviewing Assignment 4
today - Due Tuesday, July 18 at midnight
- Package not required
- Come see me if you are having problems getting
your code to work - Questions?
6The toString Method
- Special method in Java classes
- Produces a String object based on the current
object, suitable for printing - Mapped to the '' operator (concatenation)
- Also called when the object is a parameter in a
print() or println() method - There is a default toString method, but it's
better if we write our own
7toString Example
8Finalizers
- Automatically execute when class object goes out
of scope - Have no parameters
- Only one finalizer per class
- Name of finalizer finalize()
9Multiple Classes
- So far, we have added methods to the main class
- Classes extend the concept of data types data
operations - Define new classes and instantiate objects
10Multiple files
- Good style one class per file
- Store all related files in one directory
- Create jGRASP project (.gpj)
- Demo
11Multiple Objects
- A class has one single definition
- We can instantiate multiple objects of one class
- Each object keeps its own copy of the data
members - Objects are accessed using reference variables
- To perform operations on objects
referenceVariable.method (parameter1, parameter2,
)
12Multiple Classes and Objects
- Concept Candy Machine
- Objects of class type CashRegister
- cashRegister
- Objects of class type Dispenser
- Candy
- Chip
- Gum
- Cookies
- Define each class in one file each, and
instantiate objects in other classes or in the
main method
13Creating Packages
- You can create packages using a reserved word
package. - Define the class to be public. (If class is not
public, it can only be used within package.) - Choose name for package.
- Organize package (create subdirectories).
14Creating Package for class Clock
// place file in subdirectory //
jpfpatpd/ch08/clockPackage package
jpfpatpd.ch08.clockPackage public class
Clock //put instance variables and
methods, //as before, here
import jpfpatpd.ch08.clockPackage.Clock
15CandyMachine.java
- CandyMachine.main()
- Instantiates multiple objects
- Calls other CandyMachine Methods
- Other CandyMachine methods
- Calls methods of other objects
- Demonstrate flow through different methods with
the debugger
16Chapter 9 ObjectivesArrays
- Learn about arrays
- Explore how to declare and manipulate data into
arrays - Understand the meaning of array index out of
bounds - Become familiar with the restrictions on array
processing - Discover how to pass an array as a parameter to a
method - Discover how to manipulate data in a
two-dimensional array
17Arrays
- An array is a list of values that can be
represented by one variable - Members of an array must all have the same data
type - Each value is stored at a specific, numbered
position in the array - the number corresponding to each position is
called an index or subscript - All arrays have a length
- number of elements the array can hold
- Length accessed by arrayName.length
18Declaring Arrays
type name
The array (variable) name which is a reference
variable
Creates a reference variable called name that can
point to an array of type elements.
19Declaring ArraysExamples
// array of counters (integers) int counter
// array of characters char characterSet
// array of grades (doubles) double grade
20Instantiating Arrays
- You must instantiate (create) arrays
- the size of an array is typically not known
before run time
The new operator
name new type size
The array (element) data type
The assignment operator
21Instantiating ArraysExamples
// instantiate an array of counters int
counter counter new int5
0 lt index lt size
// instantiate the array of grades double
grade numStudents 10 grade new
doublenumStudents
22Declaration InstantiationExamples
type name new typesize
int counter 100 int intValues new
int100 char chars new charcounter Rectan
gle rectangleArray new Rectanglecounter Cli
ent myClients new Client(100)
for(int i0 iltcounter i) intValuesi
i charsi '0' rectangleArrayi new
Rectangle(i, i1) myClientsi new
Client(100)
float floatValues 1.1, 1.2, 1.3
23Array Bounds
- Arrays have finite size
- If you access an element outside of the array,
youll get an ArrayIndexOutOfBounds Exception
Example int grades 99, 98, 95, 96 //
valid index 0, 3 System.out.println (grades4)
24Example
Specify Array Size During Program Execution
(Assume that keyboard has already been declared
and instantiated.)
int arraySize System.out.print ("Enter the size
of the array") arraySize Integer.parseInt(ke
yboard.readLine()) int list new
intarraySize
25Example
Initialize Array to Specific Value (10.00)
(Assume that sale has already been declared and
instantiated.)
for (int ind 0 ind lt sale.length ind)
saleind 10.00
26Example
Print Array
(Assume that sale has already been declared and
instantiated.)
for (int ind 0 ind lt sale.length ind)
System.out.print(saleind " ")
27Example
Find Sum and Average of Array
(Assume that sale has already been declared and
instantiated, and that sum and average have
already been declared.)
sum 0 for(int ind 0 ind lt sale.length
ind) sum sum saleind if(sale.l
ength ! 0) average sum /
sale.length else average 0.0
28Example
Determining Largest Element in Array
(Assume that sale has already been declared and
instantiated, and that maxIndex and largestSale
have already been declared.)
maxIndex 0 for (int ind 1 ind lt
sale.length ind) if (salemaxIndex lt
saleind) maxIndex ind
largestSale salemaxIndex
5
7
0
1
2
3
4
6
25.00
19.60
12.50
8.35
14.00
39.43
98.23
35.90
29Parallel Arrays
- Arrays are parallel if corresponding components
hold related information
String studentName double studentGPA
For example, studentName and studentGPA are
parallel if studentGPA3 is the GPA of the
student with studentName3.
30In-Class Exercises
- Declare an array of integers called numbers
- Hint type name
- Declare and instantiate an array of 26 characters
called alphabet - Hint type name new typesize
-
int numbers
char alphabet new char26
31In-Class Exercises
- Declare an array of 5 characters called grades
and initialize it with the letters A, B, C, D, F - Hint type name initialization list
- Write a loop to print the contents of an array
named zipCodes - Hint to access array element nameindex
char grades 'A', 'B', 'C', 'D', 'F'
for (int i0 iltzipCodes.length i)
System.out.println (zipCodesi)
32In-Class Exercises
- Write a loop to change all the values of the
integer array numbers to index 1
for (int i0 iltnumbers.length i)
numbersi i1
33Arrays - Summary
- Why use them?
- maintain a list of related and similar items
(from the same type) - How to?
- first declare a variable to reference the array
- when your program knows how many elements, it can
then instantiate (create), initialize, and access
the array - design code to index the array within, and only
within the array bounds
34To do
- Read
- Chapter 9
- Pages 543-557, 567-583
- Chapter 10
- Pages 609-630
- Assignment 5
- Due Monday, July 17 at midnight
- Next Lecture
- More on arrays and sorting by using arrays
- Quiz
- Some time this week (could be tomorrow!)