CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.

Slides:



Advertisements
Similar presentations
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Arrays part 3 Multidimensional arrays, odds & ends.
Arrays Chapter 6 Chapter 6.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
CS102--Object Oriented Programming Discussion 1: – Project 4 on Page 328 – The use of arrays Copyright © 2008 Xiaoyan Li.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
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,
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
Arrays 4/4 By Pius Nyaanga. Outline Multidimensional Arrays Two-Dimensional Array as an Array of Arrays Using the length Instance Variable Multidimensional.
Arrays in Classes and Methods
Arrays 3/4 By Pius Nyaanga.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Arrays 2/4 By Pius Nyaanga.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Java How to Program, Late Objects Version, 10/e
Multidimensional Arrays Section 6.4
Arrays 3/4 June 3, 2019 ICS102: The course.
Chapter 6 Arrays.
Arrays.
Presentation transcript:

CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li

Programming tips: Comments/documentations Document general information about author, date, function of your program/class at the very beginning. – /* */ – // – /** */ Make comments for methods and instance variables

Programming tips: interaction with users Display message telling the user what to do if your programming is expecting input for the user. Echo input to make sure user’s input is correctly loaded. Check whether user’s input is valid.

Review on arrays 1. When do you use an array? 2. What is the base type of an array? 3. How do you create an array? 4. What are the two ways to initialize an array? 5. How to access each element in an array? 6. How do you check whether two arrays contain the same elements? 7. Can arrays be parameters for your method? 8. Can you return an array in your method? 9. What is selection sort? Can you implement the selection sort algorithm in Java?

Question: Is an Array of Characters a String An array of characters is conceptually a list of characters, and so is conceptually like a string However, an array of characters is not an object of the class String char[] a = {'A', 'B', 'C'}; String s = a; //Illegal! An array of characters can be converted to an object of type String, however 6-5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

An Array of Characters Is Not a String The class String has a constructor that has a single parameter of type char[] String s = new String(a); – The object s will have the same sequence of characters as the entire array a ( "ABC" ), but is an independent copy Another String constructor uses a subrange of a character array instead String s2 = new String(a,0,2); – Given a as before, the new string object is "AB" 6-6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arguments for the Method main The heading for the main method of a program has a parameter for an array of String – It is usually called args by convention public static void main(String[] args) – Note that since args is a parameter, it could be replaced by any other non-keyword identifier If a Java program is run without giving an argument to main, then a default empty array of strings is automatically provided 6-7 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arguments for the Method main Here is a program that expects three string arguments: public class SomeProgram { public static void main(String[] args) { System.out.println(args[0] + " " + args[2] + args[1]); } Note that if it needed numbers, it would have to convert them from strings first 6-8 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arguments for the Method main If a program requires that the main method be provided an array of strings argument, each element must be provided from the command line when the program is run java SomeProgram Hi ! there – This will set args[0] to "Hi", args[1] to "!", and args[2] to "there" – It will also set args.length to 3 When SomeProgram is run as shown, its output will be: Hi there! 6-9 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Exercise: Write a method that tests two integer arrays to see if they are equal (of same length & contain the same integer values) 6-10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved Compare two arrays

equalsArray: 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; } 6-11 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The Arrays class In java.util package contains various static methods for manipulating arrays (such as sorting and searching). – public static int binarySearch(int[] a, int key) Searches the specified array of ints for the specified value using the binary search algorithm.binarySearch – pubic static boolean equals(int[] a, int[] a2) Returns true if the two specified arrays of ints are equal to one another.equals – public static void fill(int[] a, int val) Assigns the specified int value to each element of the specified array of intsfill

The Arrays class More methods – public static void sort(int[] a) Sorts the specified array of ints into ascending numerical order.sort – public static void sort(int[] a, int fromIndex, int toIndex) Sorts the specified range of the specified array of ints into ascending numerical order.sort Exercise: Write a piece of code that tests two integer arrays to see if they are equal using the Arrays class.

Exercise: There are 5 registered students in our class. Each takes 4 courses this semester. Write a program that read scores from keyboard, calculate the average score for each student and output the average scores from the highest to the lowest.

Multidimensional Arrays It is sometimes useful to have an array with more than one index Multidimensional arrays are declared and created in basically the same way as one-dimensional arrays – You simply use as many square brackets as there are indices – Each index must be enclosed in its own brackets double[][]table = new double[100][10]; int[][][] figure = new int[10][20][30]; Person[][] = new Person[10][100]; 6-15 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Multidimensional Arrays Multidimensional arrays may have any number of indices, but perhaps the most common number is two – Two-dimensional array can be visualized as a two- dimensional display with the first index giving the row, and the second index giving the column char[][] a = new char[5][12]; – Note that, like a one-dimensional array, each element of a multidimensional array is just a variable of the base type (in this case, char ) 6-16 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Multidimensional Arrays In Java, a two-dimensional array, such as a, is actually an array of arrays – The array a contains a reference to a one-dimensional array of size 5 with a base type of char[] – Each indexed variable ( a[0], a[1], etc.) contains a reference to a one-dimensional array of size 12, also with a base type of char[] A three-dimensional array is an array of arrays of arrays, and so forth for higher dimensions 6-17 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Two-Dimensional Array as an Array of Arrays (Part 1 of 2) 6-18 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Question: How to access every element in a two-dimensional array? char[][] a = new char[5][12];

Two-Dimensional Array as an Array of Arrays (Part 2 of 2) 6-20 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Using the length Instance Variable char[][] page = new char[30][100]; The instance variable length does not give the total number of indexed variables in a two-dimensional array – Because a two-dimensional array is actually an array of arrays, the instance variable length gives the number of first indices (or "rows") in the array page.length is equal to 30 – For the same reason, the number of second indices (or "columns") for a given "row" is given by referencing length for that "row" variable page[0].length is equal to Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Using the length Instance Variable The following program demonstrates how a nested for loop can be used to process a two- dimensional array – Note how each length instance variable is used int row, column; for (row = 0; row < page.length; row++) for (column = 0; column < page[row].length; column++) page[row][column] = 'Z'; 6-22 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Ragged Arrays Each row in a two-dimensional array need not have the same number of elements – Different rows can have different numbers of columns An array that has a different number of elements per row it is called a ragged array 6-23 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Create Ragged Arrays double[][] a = new double[3][5]; The above line is equivalent to the following: double [][] a; a = new double[3][]; //Note below a[0] = new double[5]; a[1] = new double[5]; a[2] = new double[5]; – Note that the second line makes a the name of an array with room for 3 entries, each of which can be an array of doubles that can be of any length – The next 3 lines each create an array of doubles of size Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Create Ragged Arrays double [][] a; a = new double[3][]; Since the above line does not specify the size of a[0], a[1], or a[2], each could be made a different size instead: a[0] = new double[5]; a[1] = new double[10]; a[2] = new double[4]; 6-25 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 6-26 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 6-27 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 6-28 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 6-29 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

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

Quiz: There are 5 registered students in our class. Each takes 4 courses this semester. Write a program that read scores from user’s input, calculate the average score for each student and output the average scores from the highest to the lowest.

Announcement Next Lecture: Inheritance Reading assignment: Chapter 7