Mar 3 - Joshua Stough

Download Report

Transcript Mar 3 - Joshua Stough

CSCI 51
Introduction to Programming
March 3, 2009
Today
• Review
• Reserved word this
• Arrays
Announcements
• Program 5
Review
Scope
public class Rectangle
{
// variables declared here are class-level
// available in all methods in Rectangle class
public int computeArea()
{
// variables declared here are method-level
// only available in computeArea()
}
public void print()
{
// variables declared here are method-level
// only available in print()
}
}
Review
Visibility Modifiers
• public visibility
– can be accessed from
anywhere
public class Rectangle
{
private int length;
private int width;
• private visibility
public Rectangle ()
{
length = 0;
width = 0;
}
– can only be accessed
from inside the class
(inside the same Java
source file)
...
}
Review
Visibility Modifiers
• Usually declare data members with private
visibility
• Declare methods that clients (other classes)
are supposed to call with public visibility
– service methods
• Declare methods that only other methods in
the class are supposed to call with private
visibility
– support methods
The Reference this
• Reserved word
• Refers to instance variables and
methods of a class
• Allows you to distinguish between
member variables and local variables
with the same name
Rectangle.java
public class Rectangle
{
private int length;
private int width;
public Rectangle (int length, int width)
{
this.length = length;
this.width = width;
}
Reference Variables as
Parameters
If a formal parameter is a reference
variable:
– copies value of corresponding actual
parameter
– value of actual parameter is address of
object where actual data is stored
– both formal and actual parameter refer to
same object
Review
Overloading Methods
• Overloading - the process of using the same method
name for multiple methods
• The signature of each overloaded method must be
unique
– number of parameters
– type of the parameters
– not the return type of the method, though
• The compiler determines which version of the method
is being invoked by analyzing the parameters
Review
Rectangle r2 = new Rectangle (5, 10);
public class Rectangle
{
private int length;
private int width;
public Rectangle ()
{
length = 0;
width = 0;
}
public Rectangle (int l, int w)
{
length = l;
width = w;
}
Review
• A method should be relatively small
– it should be able to be understood as a single
entity
– its name should fully describe its function
• A potentially large method should be
decomposed into several smaller methods as
needed for clarity
• A service method of an object may call one or
more support methods to accomplish its goal
Thought Exercise
Write a method for the Rectangle class called
printBox that will print the rectangle as a
box made of %
example: length = 3, width = 5
%%%%%
%
%
%%%%%
public void printBox ()
{
for (int i = 1; i <= width; i++)
System.out.print("%");
System.out.println( );
for (int i = 1; i <= length - 2; i++) {
System.out.print("%");
for (int j = 1; j <= width - 2; j++)
System.out.print(" ");
System.out.println("%");
}
length = 3, width = 8
}
for (int i = 1; i <= width; i++) %%%%%%%%
System.out.print("%");
%
%
System.out.println( );
%%%%%%%%
The toString Method
• Special method in Java classes
• Produces a String object based on the
current object, suitable for printing
• Mapped to the '+' operator
• 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
Rectangle.java
public String toString()
{
String result = "";
result += "length: " + length + "\n";
result += "width: " + width;
return (result);
}
Rectangle r = new Rectangle (2,3);
System.out.println (r);
length: 2
width: 3
The Modifier static
• In the method heading, specifies that the
method can be invoked by using the name of
the class
– no object has to be created in order to use the
method
– can't call a non-static method from a static method
– can't access non-static variables from a static
method
• If used to declare data member, data member
invoked by using the class name
– no object has to be created in order to use the
variables
static Variables
• Shared among all objects of the class
• Memory created for static variables when
class is loaded
– memory created for instance variables (non-static)
when an object is instantiated (using new)
• If one object changes the value of the static
variable, it is changed for all objects of that
class
public class Illustrate
Illustrate obj1 = new Illustrate(3);
{
private int x;
Illustrate obj2 = new Illustrate(5);
public static int y;
private static int count;
Illustrate Class
public Illustrate()
{
x = 0;
}
public Illustrate (int a)
{
x = a;
}
y
count
01
0
1
obj1
x
3
x
5
obj2
public static void incrementCount()
{
count++;
Illustrate.incrementCount();
}
}
Illustrate.y++;
Arrays
0
1
2
• 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
3
Declaring Arrays
The array (element)
data type
0
1
2
Empty square brackets
type[] name;
The array (variable) name
Creates a reference variable called name that
can point to an array of type elements.
3
Declaring Arrays
0
1
2
Examples
// array of counters (integers)
int[] counter;
// array of characters
char[] characterSet;
// array of grades (doubles)
double[] grade;
counter
characterSet
grade
3
Instantiating Arrays
0
1
2
3
You must instantiate (create) arrays
– the size of an array is typically not known
before run time
The assignment operator
The array
(variable) name
The new operator
name = new type[size];
The array (element)
data type
The number of
elements
Instantiating Arrays
0
1
2
3
Examples
// instantiate an array of counters
counter = new int[5];
0
1
0 <= index < size
2
3
4
// instantiate the array of grades
numStudents = 10;
grade = new double[numStudents];
counter
Declaration and
Instantiation
0
1
2
type[] name = new type[size];
Declaration
Instantiation
3
Arrays of Objects
• Can use arrays to manipulate objects
• Create array of objects
classname[] array = new classname[size];
• Must instantiate each object in array
for(int j=0; j <array.length; j++) {
array[j] = new classname();
}
Example
0
1
int[] num = new int[5];
2
3
Array Access
0
1
2
3
Examples
double score[] = new double[3];
score[0] = 98.3;
score[1] = 57.8;
score[2] = 93.4;
averageScore = (score[0]+score[1]+score[2])/3;
numStudents = 3;
often use loops for access
totalScore = 0;
for (int i = 0; i < numStudents; i++) {
totalScore += score[i];
}
averageScore = totalScore/numStudents;
Array Length
0
1
2
Arrays have length
– an internal variable called length
– number of elements in array
– access the length variable using the “dot’
notation (arrayname.length)
// loop through the array of test scores
sumOfScores = 0;
for (int i=0; i<scores.length; i++) {
sumOfScores += scores[i];
}
3
Initializing Arrays
0
1
2
3
• Array elements are variables too!
– if you don’t initialize, the contents are
undefined
• When and how?
– if you don’t yet know the size
• initialize at run time, typically with a loop
– if you know how many elements
• perhaps use an initializer list
int counter[] = {0, 0, 0, 0, 0};
char[] characterSet = {‘a’,’b’,’c’}; // etc.
Initializer Lists
0
1
2
• Lists the initial value for the elements of an
array
• Items are separated by commas and the list
is in braces {}
• The size of the array is determined by the
number of items in the list
int[] scores = {87, 98, 45};
• Can only be used in the same statement as
declaring the array
NOT int[] scores;
scores = {87, 98, 45};
3
Array Bounds
0
1
2
• Arrays have finite size
• If you access an element outside of the
array, you’ll get an
ArrayIndexOutOfBounds Exception
Example:
int[] grades = {99, 98, 95, 96};
System.out.println (grades[4]);
3
Example
0
1
2
3
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(keyboard.readLine());
int[] list = new int[arraySize];
Example
0
1
2
3
Initialize Array to Specific Value (10.00)
(Assume that sale has already been declared and instantiated.)
for (int ind = 0; ind < sale.length; ind++) {
sale[ind] = 10.00;
}
Example
0
1
2
3
Read Data into Array
(Assume that sale has already been declared and instantiated,
and that keyboard has already been declared and instantiated.)
for (int ind = 0; ind < sale.length; ind++) {
sale[ind] = Double.parseDouble(keyboard.readLine());
}
Example
0
1
2
3
Print Array
(Assume that sale has already been declared and instantiated.)
for (int ind = 0; ind < sale.length; ind++) {
System.out.print(sale[ind] + " ");
}
Example
0
1
2
3
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 < sale.length; ind++) {
sum = sum + sale[ind];
}
if(sale.length != 0)
average = sum / sale.length;
else
average = 0.0;
0
Example
1
2
3
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 < sale.length; ind++) {
if (sale[maxIndex] < sale[ind]) {
maxIndex = ind;
}
}
largestSale = sale[maxIndex];
0
12.50
1
8.35
2
19.60
3
25.00
4
14.00
5
39.43
6
98.23
7
35.90
Parallel Arrays
0
1
Arrays are parallel if corresponding
components hold related information
String[] studentName;
double[] studentGPA;
For example, studentName and
studentGPA are parallel if
studentGPA[3] is the GPA of the
student with studentName[3].
2
3
In-Class Exercises
1.
0
1
2
Declare an array of integers called numbers
Hint: type[] name;
int[] numbers;
2.
Declare and instantiate an array of 26 characters
called alphabet
Hint: type[] name = new type[size];
char[] alphabet = new char[26];
3
In-Class Exercises
3.
0
1
2
3
Declare an array of 5 characters called grades and
initialize it with the letters: A, B, C, D, F
Hint: type[] name = {initialization list};
char[] grades = {'A', 'B', 'C', 'D', 'F'};
4.
Write a loop to print the contents of an array named
zipCodes
Hint: to access array element name[index]
for (int i=0; i<zipCodes.length; i++) {
System.out.println (zipCodes[i]);
}
In-Class Exercises
0
1
2
5. Write a loop to change all the values of the
integer array numbers to index + 1
for (int i=0; i<numbers.length; i++) {
numbers[i] = i+1;
}
3
Arrays
0
1
2
Summary
• Why use them?
– maintain a list of related items
• How use them?
– 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 only within the
array bounds
3
Review
0
1
2
3
Arrays
• Declaration
int[] counts;
• Instantiation
counts = new int[50];
• Initialization / Access
for (int i=0; i<counts.length; i++) {
counts[i] = 0;
}
• Initializer List
– declaration, instantiation, and initialization
double[] grades = {98.7, 72.4, 87.5};
int[] numbers = {num, num+1, num+2, num+3};
can use variables and
expressions as initial values
Next Time in CSCI 51
• More on Arrays
• Reading Assignment: Ch 10