Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.

Similar presentations


Presentation on theme: "Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved."— Presentation transcript:

1 Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved

2 Creating and Accessing Arrays
double[] score = new double[5]; ====================================== double[] score; score = new double[5]; ======================================== int count = 5; double[] score = new double[count]; ========================================== score[0], score[1], score[2], score[3], score[4], score.length Copyright © 2008 Pearson Addison-Wesley. All rights reserved

3 Creating and Accessing Arrays
char[] line = new char[80]; double[] reading = new double[count]; Date[] birthdays = new Date[100]; line.length reading.length birthday.length Copyright © 2008 Pearson Addison-Wesley. All rights reserved

4 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Working with Arrays Scanner in = new Scanner(System.in); System.out.println("Enter number of students"); int count = in.nextInt(); double[] score = new double[count]; for (int i = 0; i < score.length; i++){ System.out.println("Enter each student’s score "); score[i] = in.nextDouble(); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Working with Arrays for (int i = 0; i < score.length; i++){ System.out.println(“The score of student “ + (i+1) + “ is ”+ score[i]); } double sum = 0; sum = sum + score[i]; System.out.println(“The average score is “ + sum/score.length); Copyright © 2008 Pearson Addison-Wesley. All rights reserved

6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Working with Arrays for (int i = 0; i < score.length; i++){ System.out.println(“The score of student “ + (i+1) + “ is ”+ score[i]); } double highest = score[0]; for (int i = 1; i < score.length; i++){ if (score[i] > highest ) hightest = score[i]; System.out.println(“The highest score is “ + highest); Copyright © 2008 Pearson Addison-Wesley. All rights reserved

7 Practice declare array
Make an array of integers called grades for a class of 25 students Make an array of Strings called names that holds 21 names.

8 Practice declare array
Make an array of integers called grades for a class of 25 students int [ ] grades = new int[25]; Make an array of Strings called names that holds 21 names. String [] names = new String [21];

9 Array index out of bounds
Very common error Trying to use an index for the array that does not exist int [ ] scores = new int [5] for (int i=0; i<=5; i++) score[i]= in.nextDouble(); or – for (int i=0; i < 5; i++) score [i]= score [i+1];

10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Initializing Arrays int[] age = {2, 12, 1}; ============================================== char[] a = {'A', 'B', 'C'}; ============================================= double[] reading = new double[100]; int index; for (index = 0; index < reading.length; index++) reading[index] = 42.0; reading[0], reading[1], ...reading[98], reading[99] Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11 Array practice - initialize
Declare and initialize a String array with the names {“Tom”,Sue”,”Bob”} Declare an array called grades. Initialize with random numbers between 50 and 100

12 Array practice - initialize
Declare and initialize a String array with the names {“Tom”,Sue”,”Bob”} String[] names ={ “Tom”, “Sue”, ”Bob”}

13 Array practice - initialize
Declare an array called grades. Initialize with 7 random numbers between 50 and 100 Random rand=new Random(); int[] grades = new int[7]; for(int i=0;i<7;i++){ grades[i]= rand.nextInt(51)+50; }

14 The Random class A Random object generates pseudo-random* numbers.
Class Random is found in the java.util package. import java.util.*; Example: Random rand = new Random(); int randomNumber = rand.nextInt(10); // 0-9 Method name Description nextInt() returns a random integer nextInt(max) returns a random integer in the range [0, max) in other words, 0 to max-1 inclusive nextDouble() returns a random real number in the range [0.0, 1.0)

15 using loops to initialize arrays
Loops are a powerful tool to loop through positions in arrays Beware: Begin at 0 and End at (length -1) for(i=0; i<a.length; i++){ a[i]= i *2; }

16 Practice initialize using keyboard
Declare and initialize an array of 10 ints reading in each integer from keyboard

17 Practice initialize using keyboard
Declare and initialize an array of 10 ints reading in each integer from keyboard Scanner input = new scanner(System.in); int[] a = new int[10] for(int i=0; i< a.length ; i++){ System.out.println(“enter integer”); a[i]=input.nextInt(); }

18 practice using keyboard to get length
Ask the user to enter an integer and then declare an array of that length and initialize

19 practice using keyboard to get length
System.out.println(“Enter length”); int arrayLength=input.nextInt(); int [] a = new int[arrayLength]; for (int i=0; i<a.length ;i++){ a[i]=i; }

20 When use == or = review Use == when you are testing 2 values to see if they are equal if( a[i] == 100) Use = when assigning a value a[i] = 100;

21 Practice array and loop combinations
Declare an array of 10 integers and initialize with the even numbers from 2 to 20

22 Practice array and loop combinations
Declare an array of 10 integers and initialize with the even numbers from 2 to 20 int [] a = new int [10]; for(int i=0; i < a.length; i++){ a[i] = (i+1)*2; }

23 Practice Sum the numbers in an array Print sum and average
Do in Jgrasp

24 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Array Parameters The following method, doubleElements, specifies an array of double as its single argument: public class SampleClass { public static void doubleElements(double[] a) int i; for (i = 0; i < a.length; i++) a[i] = a[i]*2; . . . } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

25 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Array Parameters Arrays of double may be defined as follows in main method: double[] a = new double[10]; double[] b = new double[30]; Given the arrays above, the method doubleElements from class SampleClass can be invoked as follows: SampleClass.doubleElements(a); SampleClass.doubleElements(b); Note: static method is called by className.methodName Copyright © 2008 Pearson Addison-Wesley. All rights reserved

26 doubleElements (number);
public class SampleClass { public static void doubleElements(double[] a){ int i; for (i = 0; i < a.length; i++) a[i] = a[i]*2; } public static void main(String[] args) { double[] score = {3.5, 2.5, 10}; double[] number = {100, 200, 45, 23.5, 35.8, 12, 56.9}; int index; System.out.println(“Original score array:” ); for (index = 0; index < score.length; index++) System.out.println(score[index] ); System.out.println(“Original number array:”); for (index = 0; index < number.length; index++) System.out.println(number[index] ); doubleElements (score); doubleElements (number); System.out.println(“new score array: “); System.out.println(“new number array: “); }//end main }//end class

27 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
EqualsArray Method public static boolean equalsArray(int[] a, int[] b) { if (a.length != b.length) return false; else int i = 0; while (i < a.length) if (a[i] != b[i]) return false; i++; } return true; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

28 Practice Writing a Driver
Write a driver to test equalsArray method

29 Methods That Return an Array
public static int[] incrementArray(int[] a, int increment) { int[] temp = new int[a.length]; int i; for (i = 0; i < a.length; i++) temp[i] = a[i] + increment; return temp; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

30 int[] newNumber=incrementArray (number,100);
public class SampleClass1 { public static int[] incrementArray(int[] a, int increment){ int[] temp = new int[a.length]; int i; for (i = 0; i < a.length; i++) temp[i] = a[i] + increment; return temp; } public static void main(String[] args) { int[] score = {3, 2, 10}; int[] number = {100, 200, 45, 2, 35, 12, 56}; int index; System.out.println(“Original score array:” ); for (index = 0; index < score.length; index++) System.out.println(score[index] ); System.out.println(“Original number array:”); for (index = 0; index < number.length; index++) System.out.println(number[index] ); int[] newScore = incrementArray (score,10); int[] newNumber=incrementArray (number,100); System.out.println(“new score array: “); for (index = 0; index < score.length; index++) System.out.println(newScore[index] ); System.out.println(“new number array: “); for (index = 0; index < number.length; index++) System.out.println(newNumber[index] ); }//end main }//end class

31 Multidimensional Arrays
double[][] a = new double[3][2]; int[][][] figure = new int[10][20][30]; Person[][] p = new Person[10][100]; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

32 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
One dimensional Array double[] b = {42.0, 42.0, 42.0, 42.0, 42.0}; double[] b = new double[5]; for (int i = 0; i < b.length; i++) b[i] = 42.0; for (int i = 0; i < b.length; i++) System.out.println( b[i]); Copyright © 2008 Pearson Addison-Wesley. All rights reserved

33 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Two dimensional Array double[][] b = {{42.0, 42.0, 42.0, 42.0, 42.0}, {42.0, 42.0, 42.0, 42.0, 42.0}, {42.0, 42.0, 42.0, 42.0, 42.0} }; double[][] b = new double[3][5]; for (int i = 0; i < b.length; i++) for (int j = 0; j < b[i].length; j++) b[i][j] = 42; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

34 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Two dimensional Array for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[i].length; j++) { System.out.println( b[i][j]); } } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

35 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Ragged 2D Array double[][] b = { {1, 3, 5}, {35, 26, 10, 5}, {42.0, 42.0} }; for (int i = 0; i < b.length; i++) for (int j = 0; j < b[i].length; j++) System.out.println( b[i][j] ); Copyright © 2008 Pearson Addison-Wesley. All rights reserved

36 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Ragged 2D Array double [][] b; b = new double[3][]; b[0] = new double[3]; b[1] = new double[4]; b[2] = new double[2]; for (int i = 0; i < b.length; i++) for (int j = 0; j < b[i].length; j++) b[i][j] = 42; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

37 Multidimensional Array Parameters and Returned Values
Methods may have multidimensional array parameters They are specified in a way similar to one-dimensional arrays They use the same number of sets of square brackets as they have dimensions public void myMethod(int[][] a) { } The parameter a is a two-dimensional array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

38 Multidimensional Array Parameters and Returned Values
Methods may have a multidimensional array type as their return type They use the same kind of type specification as for a multidimensional array parameter public double[][] aMethod() { } The method aMethod returns an array of double Copyright © 2008 Pearson Addison-Wesley. All rights reserved

39 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
A Grade Book Class As an example of using arrays in a program, a class GradeBook is used to process quiz scores Objects of this class have three instance variables grade: a two-dimensional array that records the grade of each student on each quiz studentAverage: an array used to record the average quiz score for each student quizAverage: an array used to record the average score for each quiz Copyright © 2008 Pearson Addison-Wesley. All rights reserved

40 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
A Grade Book Class The score that student 1 received on quiz number 3 is recorded in grade[0][2] The average quiz grade for student 2 is recorded in studentAverage[1] The average score for quiz 3 is recorded in quizAverage[2] Note the relationship between the three arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved

41 The Two-Dimensional Array grade
Copyright © 2008 Pearson Addison-Wesley. All rights reserved

42 Example of Two-Dimensional Array
GradeBook GradeBookDemo Copyright © 2008 Pearson Addison-Wesley. All rights reserved

43 public class GradeBook { private int numberOfStudents; // Same as studentAverage.length. private int numberOfQuizzes; // Same as quizeAverage.length private int[][] grade; //numberOfStudents rows and numberOfQuizzes columns. private double[] studentAverage; private double[] quizAverage; public GradeBook( int[ ][ ] a) { if (a.length == 0 || a[0].length == 0) { System.out.println("Empty grade records. Aborting."); System.exit(0); } numberOfStudents = a.length; numberOfQuizzes = a[0].length; fillGrade(a); fillStudentAverage( ); fillQuizAverage( ); }

44 public GradeBook(GradeBook book) { numberOfStudents = book
public GradeBook(GradeBook book) { numberOfStudents = book.numberOfStudents; numberOfQuizzes = book.numberOfQuizzes; fillGrade(book.grade); fillStudentAverage( ); fillQuizAverage( ); }

45 public GradeBook( ) { Scanner keyboard = new Scanner(System
public GradeBook( ) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter number of students:"); numberOfStudents = keyboard.nextInt( ); System.out.println("Enter number of quizzes:"); numberOfQuizzes = keyboard.nextInt( ); grade = new int [numberOfStudents][numberOfQuizzes];

46 for (int studentNumber = 1; studentNumber <= numberOfStudents; studentNumber++) {
for (int quizNumber = 1; quizNumber <= numberOfQuizzes; quizNumber++) { System.out.println("Enter score for student number " + studentNumber); System.out.println("on quiz number " + quizNumber); grade[studentNumber - 1][quizNumber - 1] = keyboard.nextInt( ); }// end of inner for loop fillStudentAverage( ); fillQuizAverage( ); } //end of outer for loop

47 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
private void fillGrade(int [][] a) { grade = new int[numberOfStudents][numberOfQuizzes]; for (int studentNumber = 1; studentNumber <= numberOfStudents; studentNumber++) { for (int quizNumber = 1; quizNumber <= numberOfQuizzes; quizNumber++) grade[studentNumber-1][quizNumber-1] = a[studentNumber-1][quizNumber-1]; } } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

48 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
private void fillStudentAverage( ) { studentAverage = new double[numberOfStudents]; for (int studentNumber = 1; studentNumber <= numberOfStudents; studentNumber++) { double sum = 0; for (int quizNumber = 1; quizNumber <= numberOfQuizzes; quizNumber++){ sum = sum + grade[studentNumber - 1][quizNumber - 1]; } //end of inner for loop studentAverage[studentNumber - 1] = sum / numberOfQuizzes; }//end of outer for loop } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

49 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
private void fillQuizAverage( ) { quizAverage = new double[numberOfQuizzes]; for (int quizNumber = 1; quizNumber <= numberOfQuizzes; quizNumber++) { double sum = 0; for (int studentNumber = 1; studentNumber <= numberOfStudents; studentNumber++) { sum = sum + grade[studentNumber - 1][quizNumber - 1]; }//end of inner for loop quizAverage[quizNumber - 1] = sum / numberOfStudents; }//end of outer for loop } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

50 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
public void display( ) { for (int studentNumber = 1; studentNumber <= numberOfStudents; studentNumber++) { System.out.print("Student " + studentNumber + " Quizzes: "); for (int quizNumber = 1; quizNumber <= numberOfQuizzes; quizNumber++) { System.out.print(grade[studentNumber - 1][quizNumber - 1] + " "); }//end of inner for loop System.out.println(" Ave = " + studentAverage[studentNumber - 1] ); }// end of outer for loop System.out.println("Quiz averages: "); for (int quizNumber = 1; quizNumber <= numberOfQuizzes; quizNumber++) { System.out.print("Quiz " + quizNumber + " Ave = " + quizAverage[quizNumber - 1] + " "); } System.out.println( ); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

51 Copyright © 2008 Pearson Addison-Wesley. All rights reserved
public class GradeBookDemo { public static void main(String[] args) { GradeBook book = new GradeBook( ); book.display( ); } } Copyright © 2008 Pearson Addison-Wesley. All rights reserved


Download ppt "Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved."

Similar presentations


Ads by Google