Download presentation
Presentation is loading. Please wait.
1
Arrays in Classes and Methods
2
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.
3
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; }
4
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; } }
5
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( ); } }
6
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; }
7
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( ); } } }
8
Example – Sales Reporter (cont’d)
public static void main(String[ ] args) { SalesReporter clerk = new SalesReporter( ); clerk.getFigures( ); clerk.update( ); clerk.displayResults( ); } }
9
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]);
10
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] = *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; } }
11
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; }
12
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.
13
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.
14
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”.
15
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]); }
16
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.
17
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.
18
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];
19
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."); }
20
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; } }
21
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; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.