comp 10 introduction to programming mr. joshua stough october 29, 2007
Post on 15-Jan-2016
218 views
TRANSCRIPT
COMP 10Introduction to Programming
Mr. Joshua StoughOctober 29, 2007
Debugging Tips
• Pay attention to detail!– Java is case-sensitive– difference between () and [] and {}
• Double-check loop conditions• Work through errors one at a time• Add println statements to show values
of variables before/after errors occur• Take a break!
Spot the Bug
public class Errors{ public static void main (String[] args) {
int[] numbers = {8, 4, 5, 7};
for (int i=0; i<=numbers.length; i++) { System.out.println (numbers(i));}
}} Errors.java:8: cannot resolve symbol
symbol: method numbers (int)location: class Errors
System.out.println (numbers(i)); ^
1 error
Spot the Bug
public class Errors{ public static void main (String[] args) {
int[] numbers = {8, 4, 5, 7};
for (int i=0; i<=numbers.length; i++) { System.out.println (numbers[i]);}
}}
8457Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4at Errors.main(Errors.java:8)
ReviewVisibility Modifiers• public visibility
– can be accessed from anywhere
• private visibility – can only be accessed
from inside the class (inside the same Java source file)
public class Rectangle{
private int length;private int width;
}
public Rectangle (){ length = 0; width = 0;}
...
ReviewVisibility 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
Review - Constructor
public Rectangle (int l, int w){ length = l; width = w;}
public class Rectangle{
private int length;private int width;
Rectangle r2 = new Rectangle (5, 10);
public Rectangle (){ length = 0; width = 0;}
All formal parametersare local to the method.
r2500
2500
2 3
ReviewObjects• Create an object:
Rectangle r;r = new Rectangle(2, 3);ORRectangle r = new Rectangle(2, 3);
• Use the object and the dot operator to access methods:r.setLength(5);r.setWidth(10);
r
2 3
25002500
5 10
ReviewAccessing Static Members
public class Card{
public static final int ACE = 14;
public class BlackjackGame{
public static int calcPoints (Card card)
Card.ACE
BlackjackGame.calcPoints
ReviewCalling Methods
• static methods– classname.methodname
• non-static methods– create an object– objectname.methodname
Reviewthis
public class Rectangle{
private int length;private int width;
public Rectangle (int length, int width){
this.length = length; this.width = width;
}
ReviewPassing Objects as Parameters
public class BlackjackGame{ public static int calcPoints(Card c) {
}}
Card card1 = new Card (2, Card.HEARTS);
card1 face 2
suit 0
c
int points = BlackjackGame.calcPoints(card1);
2
points
Array Bounds
• 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]);
0 1 2 3
int arraySize;
System.out.print ("Enter the size of the array:"); arraySize = Integer.parseInt(keyboard.readLine());
int[] list = new int[arraySize];
Specify Array Size During Program Execution
Example0 1 2 3
(Assume that keyboard has already been declared and instantiated.)
Example
for (int ind = 0; ind < sale.length; ind++) { sale[ind] = 10.00;}
Initialize Array to Specific Value (10.00)
(Assume that sale has already been declared and instantiated.)
0 1 2 3
Example
for (int ind = 0; ind < sale.length; ind++) { sale[ind] = Double.parseDouble(keyboard.readLine());}
(Assume that sale has already been declared and instantiated, and that keyboard has already been declared and instantiated.)
Read Data into Array
0 1 2 3
Example
for (int ind = 0; ind < sale.length; ind++) { System.out.print(sale[ind] + " ");}
Print Array
(Assume that sale has already been declared and instantiated.)
0 1 2 3
Example
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;
Find Sum and Average of Array
(Assume that sale has already been declared and instantiated,and that sum and average have already been declared.)
0 1 2 3
Example
maxIndex = 0;for (int ind = 1; ind < sale.length; ind++) { if (sale[maxIndex] < sale[ind]) { maxIndex = ind;
}}largestSale = sale[maxIndex];
Determining Largest Element in Array(Assume that sale has already been declared and instantiated,and that maxIndex and largestSale have already been declared.)
0 1 2 3 4 5 6 7
12.50 8.35 19.60 25.00 14.00 39.43 35.9098.23
0 1 2 3
Parallel Arrays
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].
0 1 2 3
In-Class Exercises
1. Declare an array of integers called numbersHint: type[] name;
2. Declare and instantiate an array of 26 characters called alphabetHint: type[] name = new type[size];
int[] numbers;
char[] alphabet = new char[26];
0 1 2 3
In-Class Exercises
3. Declare an array of 5 characters called grades and initialize it with the letters: A, B, C, D, FHint: type[] name = {initialization list};
4. Write a loop to print the contents of an array named zipCodesHint: to access array element name[index]
char[] grades = {'A', 'B', 'C', 'D', 'F'};
for (int i=0; i<zipCodes.length; i++) {System.out.println (zipCodes[i]);
}
0 1 2 3
In-Class Exercises
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;
}
0 1 2 3
ArraysSummary
• 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
0 1 2 3
ReviewArrays• Declaration
int[] counts;
• Instantiationcounts = new int[50];
• Initialization / Accessfor (int i=0; i<counts.length; i++) {counts[i] = 0;
}
• Initializer List– declaration, instantiation, and initializationdouble[] grades = {98.7, 72.4, 87.5};int[] numbers = {num, num+1, num+2, num+3};
can use variables andexpressions as initial values
0 1 2 3
Arrays and Assignment
counter
01
23
4
int[] counter = new int[5];
int[] temp;
temp
temp = counter;
doesn't make a copy of the array!
temp == counter is true sincethe reference variables containthe same address
Copying Arrayscounter
01
23
4
int[] counter = {1, 2, 3, 4, 5};
1
23
4
5
int[] temp = new int[counter.length];
01
23
4
temp
for (int i=0; i<counter.length; i++) {temp[i] = counter[i];
}
1
23
4
5
i
012345
References and Assignment
counter
01
23
4
1
23
4
5
01
23
4
temp
temp = counter;
1
23
4
5
Remember that arrays use reference variables just like objects.
References and nullcounter
01
23
4
1
23
4
5
01
23
4
temp
temp = null;
1
23
4
5
Remember that arrays use reference variables just like objects.
null is a reserved wordthat means "empty"
Arrays as Parameters
• Entire array can be passed as a parameter– method can change elements of the
array permanently– since we're passing a reference
• Elements of an array can be passed as parameters, too– normal rules apply…
public class Tester{ public static void swap (int[] scores, int x, int y) {
int temp = scores[x];scores[x] = scores[y];scores[y] = temp;
}
public static void main (String[] args) {
int[] grades = new int[4];
for (int i=0; i<grades.length; i++) {grades[i] = i*10;
}
swap (grades, 2, 3); }
}
grades[2]: 20grades[3]: 30grades[2]: 30grades[3]: 20
scores[2]: 20scores[3]: 30temp : 20
scores[2]: 30scores[3]: 30temp : 20
scores[2]: 30scores[3]: 20temp : 20
Arrays as Parameters
public static void swap (int[] scores, int x, int y)
swap (grades, 2, 3);
alias
01
23
grades
0
1020
30
scores x 2
y 3
temp
int temp = scores[x];scores[x] = scores[y];scores[y] = temp;
20
20
30
Arrays of Objects
• Can use arrays to manipulate objects• Create array of objects
• Must instantiate each object in array
classname[] array = new classname[size];
for(int j=0; j <array.length; j++) {array[j] = new classname();
}
Yahtzee
• Game of Yahtzee requires 5 dice
• Die– member variable: – methods:
int face
void roll()int getFace()
Die()
Instantiating Array Objects
Die[] dice = new Die[5];
for (int i=0; i<dice.length; i++) {dice[i] = new Die();
}
01
23
4
dice
face
face
.
.
.
each element in the arrayis a reference variable
dice[0] == dice[1]
Comparing Objects== vs. equals method
dice[0].equals(dice[1])
• If equals method for the class is undefined• are the variables aliases? (i.e., do the variables contain the same address?)
• If equals method for the class is defined• depends on the implementation of equals
are the variables aliases? (i.e., do the variables contain the same address?)