Академический Документы
Профессиональный Документы
Культура Документы
An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether primitive or reference data types. For example, we may want to store:
An array of double values An array of int values
import java.util.; public class ExamScoresForLoop { public static void main(String[] args) { Scanner keyboard = new Scanner (System.in); double score; double total = 0.0; for(int i = 1; i <= 10; i++) { System.out.println("Enter score " + i +":"); score = keyboard.nextDouble(); total = total + score; } System.out.println("The average score is " + total/10); // how to display scores which are greater than average??? } }
The Problem:
We need to keep track of each score that is entered by the user in 3 an efficient manner.
Using Arrays
Instead of only storing one score:
score 98.9
0x0010
98.9
0x0010
0x0h41 0x0h42
50.5 75.0
59.5 65.4
4
in this case, score is considered to be a reference to the array at the memory address stored.
0x0h43
0x0h44
can store and access data in it. We must specify the index representing the position of the data. The index always begins from 0. Index representing
score
98.9 50.5 75.0 0 1 2 3 4
5
score[0] score[3]
59.5
65.4
Declaring Arrays
An array is declared by:
specifying the type of data it will hold specifying the name of the array with an identifier including square brackets [ ] <data type>[] <identifier>;
Syntax:
Examples
int[] num; // an array of ints double[] score; // an array of doubles Student[] st; // an array of Student objects
Creating Arrays
In Java, the array is an object and must be instantiated with its size. Syntax:
Therefore, an array may be declared and instantiated in one statement:
int[] num = new int[10]; //creates an array to store 10 integers int[] num; num = new int[10];
7
Initializer Lists
An array can also be created by using an initializer list that fills in the values of the elements in the array in one line. When an initializer list is used, the new operator and size of the array are not specified. Examples:
int[] num = {3, 6, 5, 7, 2, 8, 10, 20} char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}
8
Bounds Checking
An array that has been instantiated has a fixed size.
int[] num = new int[10] has array elements from num[0] to num[9] only.
The Java interpreter will indicate an out-ofbounds error at run-time if the array index is not valid. Each array object has an attribute length that stores the size of the array, or the number of elements. Therefore an array will have valid indices from 0 to (length-1) only.
9
Traversing Arrays
We can use a for loop to traverse the array For example, we may display each element of the array:
for (int i = 0; i < maks; i++) { System.out.println(data[i]); }
We may even use a for loop to allow the user to enter the elements of the array via interactive input.
10
Searching an Array
We may need to check if an element is in the array: We can use the following logic to check whether a name that the user enters is in the array of names declared and filled earlier: ask user for the required name Start from i = 0 assume that it is not found While the required name is not found and i < length of array
if the value at position i corresponds to the required name otherwise,
then the name is found check the next element (i = i + 1)
11
Calculations
We often need to perform calculations using some or all of the elements of the array:
total of all elements the average the element with the largest or smallest value
Assume that an array of double values has been declared and filled:
double[] score = new double[10];
12
13
double maxScore = score[0] // assume max at pos 0 for (int i = 1; i < score.length; i++) { if (score[i] > maxScore) maxScore = score[i]; // new max found } System.out.println("The maximum value is " + maxScore);
14
Example
We can solve the earlier problem now using arrays: Write a Java program that:
asks the user how many scores there, then allows the user to enter the scores. After the scores have been entered, calculate the average. Also display all the scores which are higher than the average and display the highest score.
15
The method should return the position of the employee whose name is found based on the second parameter.
16
Arrays as Parameters
The method can be defined as follows:
public static int findEmp(String[] name, String wanted) { for(int i = 0; i < name.length; i++) if (wanted.equalsIgnoreCase(name[i])) return i; // found at pos i return -1; } // not found
17
19