Arrays in Classes and Methods

Slides:



Advertisements
Similar presentations
Overloading. Overloading Basics  We have seen that you can give the same name to methods in different classes.  You can also give the same name to methods.
Advertisements

Arrays I Savitch Chapter 6.1: Introduction to Arrays.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
Constructors. Defining Constructors  A constructor is a special kind of method that is designed to perform initializations, such as giving values to.
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.
COMP More About Classes Yi Hong May 22, 2015.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
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.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
Arrays Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
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,
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
(Dreaded) Quiz 2 Next Monday.
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.
Information and Computer Sciences University of Hawaii, Manoa
Arrays 3/4 By Pius Nyaanga.
Chapter 2 Elementary Programming
Arrays 2/4 By Pius Nyaanga.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
EKT472: Object Oriented Programming
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Building Java Programs
Building Java Programs
Building Java Programs Chapter 7
CSS 161 Fundamentals of Computing Introduction to Computers & Java
An Introduction to Java – Part I, language basics
Building Java Programs
Chapter 8 Slides from GaddisText
Java so far Week 7.
int [] scores = new int [10];
Building Java Programs
Building Java Programs
Building Java Programs
برنامه نویسی پیشرفته اصول جاوا.
Arrays .
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
The Basics of Recursion
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
int [] scores = new int [10];
Announcements Lab 6 was due today Lab 7 assigned this Friday
Dr. Sampath Jayarathna Cal Poly Pomona
In this class, we will cover:
Primitive Types and Expressions
Building Java Programs
Building Java Programs
Multidimensional Arrays Section 6.4
Arrays 3/4 June 3, 2019 ICS102: The course.
Chapter 6 Arrays.
Basic Exception Handling
Programming with Arrays 1
Presentation transcript:

Arrays in Classes and Methods

Facts about Arrays Arrays can be used as instance variables in classes. Both an indexed variable of an array and an entire array can be an argument to a method. Methods can return an array value.

Example – Sales Associate import java.util.*; /** Class for sales associate records. */ public class SalesAssociate { private String name; private double sales; public SalesAssociate( ) { name = "No record"; sales = 0; } public SalesAssociate(String initialName, double initialSales) { set(initialName, initialSales); } public void set(String newName, double newSales) { name = newName; sales = newSales; }

Example – Sales Associate (cont’d) public void readInput( ) { System.out.print("Enter name of sales associate: "); Scanner keyboard = new Scanner(System.in); name = keyboard.nextLine( ); System.out.print("Enter associate’s sales: $"); sales = keyboard.nextDouble( ); } public void writeOutput( ) { System.out.println("Sales associate: " + name); System.out.println("Sales: $" + sales); } public String getName( ) { return name; } public double getSales( ) { return sales; } }

Example – Sales Reporter import java.util.*; /** Program to generate sales report. */ public class SalesReporter { private double highest; private double average; private SalesAssociate[] record;//The array object is //created in getFigures. private int numberOfAssociates; //Same as record.length public void getFigures( ) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter number of sales associates:"); numberOfAssociates = keyboard.nextInt( ); record = new SalesAssociate[numberOfAssociates]; int i; for (i = 0; i < numberOfAssociates; i++) { record[i] = new SalesAssociate( ); System.out.println("Enter data for associate " + (i + 1)); record[i].readInput( ); System.out.println( ); } }

Example – Sales Reporter (cont’d) /** Computes the average and highest sales figures. Precondition: There is at least one salesAssociate. */ public void update( ) { int i; double nextSales = record[0].getSales( ); highest = nextSales; double sum = nextSales; for (i = 1; i < numberOfAssociates; i++) { nextSales = record[i].getSales( ); sum = sum + nextSales; if (nextSales > highest) highest = nextSales; //highest sales figure so far. } average = sum/numberOfAssociates; }

Example – Sales Reporter (cont’d) /** Displays sales report on console screen. */ public void displayResults( ) { System.out.println("Average sales per associate is $" + average); System.out.println("The highest sales figure is $" + highest); System.out.println( ); int i; System.out.println("The following had the highest sales:"); for (i = 0; i < numberOfAssociates; i++) { double nextSales = record[i].getSales( ); if (nextSales == highest) { record[i].writeOutput( ); System.out.println("$" + (nextSales - average) + " above the average."); System.out.println( ); } } System.out.println("The rest performed as follows:"); for (i = 0; i < numberOfAssociates; i++) { double nextSales = record[i].getSales( ); if (record[i].getSales( ) != highest) { record[i].writeOutput( ); if (nextSales >= average) System.out.println("$" + (nextSales - average) + " above the average."); else System.out.println("$" + (average - nextSales) + " below the average."); System.out.println( ); } } }

Example – Sales Reporter (cont’d) public static void main(String[ ] args) { SalesReporter clerk = new SalesReporter( ); clerk.getFigures( ); clerk.update( ); clerk.displayResults( ); } }

Indexed Variables as Method Arguments An indexed variable can be an argument to a method in exactly the same way that any other variable of the array’s base type can be an argument. For example, possibleAverage = average(firstScore, nextScore[i]);

An Example import java.util.*; /** A program to demonstrate the use of indexed variables as arguments. */ public class ArgumentDemo { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter your score on exam 1:"); int firstScore = keyboard.nextInt( ); int[] nextScore = new int[3]; int i; double possibleAverage; for (i = 0; i < nextScore.length; i++) nextScore[i] = 80 + 10*i; for (i = 0; i < nextScore.length; i++) { possibleAverage = average(firstScore, nextScore[i]); System.out.println("If your score on exam 2 is " + nextScore[i]); System.out.println("your average will be " + possibleAverage); } } public static double average(int n1, int n2) { return (n1 + n2)/2.0; } }

Entire Arrays as Method Arguments An entire array can also be used a single argument to a method. The way you specify an array parameter in a method definition is similar to the way you declare an array, e.g., public class SampleClass { public static void incrementArrayBy2(double[] a) int i; for (i = 0; i < a.length; i++) a[i] = a[i] +2; }

Entire Arrays as Method Arguments (cont’d) When you give an entire array as an argument to a method, no square brackets are used, e.g., SampleClass.incrementArrayBy2(a); where a has been declared by double[] a = new double[10]; A method can change the values in an array. The same array parameter can be replaced with array arguments of different lengths.

Arguments for the Method main The heading for the main method of a program is as follows: public static void main(String[] args) The part String[] args make it look as though args is a parameter for an array with base type String. In fact, this is exactly the case, however, a default array of strings is automatically provided as a default argument to main when you run your program.

Arguments for the Method main (cont’d) It is possible to provide additional “string arguments” when you run a program. This is normally done by running the program from the command line of the operating system like: java TestProgram Sally Smith This will set args[0] to “Sally” and args[1] to “Smith”.

Arguments for the Method main (cont’d) These two indexed variables can be used in the method main, e.g., public class TestProgram { public static void main(String[] args) System.out.println(“Hello “ + args[0] + “ “ + args[1]); }

Arguments for the Method main (cont’d) The program out would then be: Hello Sally Smith Since the identifier args is a parameter, you can really use any name you like, however, it is traditional to use the name args for this parameter. This argument to main is an array of strings. If you want numbers, you must convert the string representations to actual numbers.

Use of = and == with Arrays Since arrays are objects, the assignment operator = and the equality operator == behave the same way as they do with other kinds of objects. The assignment statement b = a; where a and b are arrays, gives the variable b the same memory address as the variable a. That is, a and b are really just different names for the same array.

Use of = and == with Arrays (cont’d) The statements b = a; followed by a[2] = 2001; changes the value of b[2] to 2001 as well as that of a[2]. It is usually best not to use the assignment operator = (or the equality operator ==) with arrays. If you want to create an array b with the same values as a, you should write: int i; for (i= 0; i< a.length; i++) b[i] = a[i];

Equality for Arrays /** This is just a demonstration program to see how equals and == work. */ public class TestEquals { public static void main(String[] args) { int[] a = new int[3]; int[] b = new int[3]; int i; for (i = 0; i < a.length; i++) a[i] = i; for (i = 0; i < b.length; i++) b[i] = i; if (b == a) System.out.println("Equal by ==."); else System.out.println("Not equal by ==."); if (equals(b,a)) System.out.println("Equal by the equals method."); else System.out.println("Not equal by the equals method."); }

Equality for Arrays (cont’d) public static boolean equals(int[] a, int[] b) { boolean match; if (a.length != b.length) match = false; else { match = true; //tentatively int i = 0; while (match && (i < a.length)) { if (a[i] != b[i]) match = false; i++; } } return match; } }

Methods that Return Arrays In Java, a method may return an array. Example: Public static char[] vowels() { char[] newArray = new char[5]; newArray[0] = ‘a’; newArray[1] = ‘e’; newArray[2] = ‘i’; newArray[3] = ‘o’; newArray[4] = ‘u’; return newArray; }