360 likes | 555 Views
COMP 10 Introduction to Programming. Mr. Joshua Stough October 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
E N D
COMP 10Introduction to Programming Mr. Joshua Stough October 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 symbolsymbol: 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]); } } } 8 4 5 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Errors.main(Errors.java:8)
public visibility can be accessed from anywhere private visibility can only be accessed from inside the class (inside the same Java source file) ReviewVisibility Modifiers 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 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; } All formal parameters are local to the method.
r 2500 2500 3 2 ReviewObjects • Create an object: Rectangle r; r = new Rectangle(2, 3); OR Rectangle r = new Rectangle(2, 3); • Use the object and the dot operator to access methods: r.setLength(5); r.setWidth(10); r 2500 2500 3 2 5 10
ReviewAccessing Static Members public class Card { public static final int ACE = 14; Card.ACE public class BlackjackGame { public static int calcPoints (Card card) 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; }
c card1 2 2 face 0 suit ReviewPassing Objects as Parameters public class BlackjackGame { public static int calcPoints(Card c) { } } Card card1 = new Card (2, Card.HEARTS); int points = BlackjackGame.calcPoints(card1); points
0 1 2 3 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 Example Specify Array Size During Program Execution (Assume that keyboard has already been declared and instantiated.) intarraySize; System.out.print ("Enter the size of the array:"); arraySize = Integer.parseInt(keyboard.readLine()); int[] list = new int[arraySize];
0 1 2 3 Example 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; }
0 1 2 3 Example 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()); }
0 1 2 3 Example Print Array (Assume that sale has already been declared and instantiated.) for (int ind = 0; ind < sale.length; ind++) { System.out.print(sale[ind] + " "); }
0 1 2 3 Example 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 1 2 3 Example 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]; 5 7 4 6 1 3 0 2 25.00 19.60 12.50 98.23 8.35 14.00 39.43 35.90
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 • Declare an array of integers called numbers Hint: type[] name; • Declare and instantiate an array of 26 characters called alphabet Hint: type[] name = new type[size]; int[] numbers; char[] alphabet = new char[26];
0 1 2 3 In-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 elementname[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 • 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; • 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
counter 0 temp 1 2 3 4 Arrays and Assignment int[] counter = new int[5]; int[] temp; temp = counter; doesn't make a copy of the array! temp == counter is true since the reference variables contain the same address
counter 0 0 temp 1 1 2 2 3 3 4 4 i Copying Arrays int[] counter = {1, 2, 3, 4, 5}; int[] temp = new int[counter.length]; 1 1 2 2 3 3 4 4 5 5 for (int i=0; i<counter.length; i++) { temp[i] = counter[i]; } 1 4 2 5 0 3
counter 0 0 temp 1 1 2 2 3 3 4 4 References and Assignment temp = counter; 1 1 2 2 3 3 4 4 5 5 Remember that arrays use reference variables just like objects.
counter 0 0 temp 1 1 2 2 3 3 4 4 References and null null is a reserved word that means "empty" temp = null; 1 1 2 2 3 3 4 4 5 5 Remember that arrays use reference variables just like objects.
Arraysas 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); } } scores[2]: 30 scores[3]: 30 temp : 20 scores[2]: 20 scores[3]: 30 temp : 20 scores[2]: 30 scores[3]: 20 temp : 20 grades[2]: 30 grades[3]: 20 grades[2]: 20 grades[3]: 30
grades scores 2 x y 3 0 0 temp 1 10 20 2 3 30 alias Arrays as Parameters swap (grades, 2, 3); public static void swap (int[] scores, int x, int y) 20 30 int temp = scores[x]; scores[x] = scores[y]; scores[y] = temp; 20
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 Die() void roll() int getFace()
dice face face . . . 0 1 2 3 4 Instantiating Array Objects Die[] dice = new Die[5]; for (int i=0; i<dice.length; i++) { dice[i] = new Die(); } each element in the array is a reference variable
Comparing Objects== vs. equals method dice[0] == dice[1] are the variables aliases? (i.e., do the variables contain the same address?) 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