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

Slides:



Advertisements
Similar presentations
Building Java Programs
Advertisements

Building Java Programs Chapter 5
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Arrays Chapter 6 Chapter 6.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Random numbers. 2 The Random class A Random object generates pseudo-random numbers. –Class Random is found in the java.util package. import java.util.*;
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application.
Comp 248 Introduction to Programming Chapter 6 Arrays Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Topic 21 arrays - part 1 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from "Should.
Arrays 4/4 By Pius Nyaanga. Outline Multidimensional Arrays Two-Dimensional Array as an Array of Arrays Using the length Instance Variable Multidimensional.
Lesson 8: Introduction To Arrays
CSC111 Quick Revision.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
Building Java Programs
Building Java Programs
Building Java Programs Chapter 5
Building Java Programs
Arrays in Classes and Methods
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Yanal Alahmad Java Workshop Yanal Alahmad
Arrays 2/4 By Pius Nyaanga.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Arrays An Array is an ordered collection of variables
Building Java Programs Chapter 7
Building Java Programs
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Building Java Programs
Chapter 8 Multi-Dimensional Arrays
Java Language Basics.
Building Java Programs
Building Java Programs
برنامه نویسی پیشرفته اصول جاوا.
python.reset() Also moving to a more reasonable room (CSE 403)
Building Java Programs
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Announcements Lab 6 was due today Lab 7 assigned this Friday
Building Java Programs
Dr. Sampath Jayarathna Cal Poly Pomona
Suggested self-checks: Section 7.11 #1-11
CSS161: Fundamentals of Computing
Building Java Programs
Building Java Programs
File output; Arrays reading: 6.4 – 6.5, 7.1
Building Java Programs
Multidimensional Arrays Section 6.4
Building Java Programs
Chapter 6 Arrays.
Programming with Arrays 1
Presentation transcript:

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

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

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

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

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

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

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.

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];

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];

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

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

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

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; }

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)

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; }

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

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(); }

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

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; }

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;

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

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; }

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

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

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

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

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

Practice Writing a Driver Write a driver to test equalsArray method

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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( ); }

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

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];

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

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

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

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

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

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