Suppose I wanted to keep track of the test scores for a class of 100
students. I could create a separate int variable for each one:
If I wanted to calculate the average, I would have to write code that looks
like this:
Luckily, there is an easier way to do this using an array!
To keep things simple, we'll start with a class of just 5 students:
public static void main(String[] args) {
final int MAX_STUDENTS = 5;
int[] testScores = new int[MAX_STUDENTS];
testScores[0] = 95;
testScores[1] = 80;
testScores[2] = 85;
testScores[3] = 70;
testScores[4] = 90;
System.out.println("Test average: " + average);
}
PROGRAM OUTPUT:
csc% java Test
Test average: 84.0
We can use an "initializer list" to create an array and give it values at the same time:
int[] testScores = {95, 80, 85, 70, 90};
We can find how the number of items in an array by using the length variable (every
array in Java has its own length variable):
int numberOfScores = testScores.length;
We can create another name (reference) for an array and use it to access the same array:
int[] listOfScores = testScores;
listOfScores[3] = 50;
How could we create an array called numbers that contains the values 10, 20, 30, 40, 50, 60, 70, 80, 90,
100?
public class Array {
/**
* Returns the sum of the values in the array
*/
public static int sum(int[] array) {
}
/**
* Returns the minimum value in the array
*/
public static int min(int[] array) {
}
/**
* Returns a String representing the array
* For example: [2, 4, 9]
*/
public static String getString(int[] array) {
}
/**
* Returns a copy of the array
*/
public static int[] copy(int[] array) {
}
/**
* Returns a copy of the array in reverse order
*/
public static int[] reverse(int[] array) {
}
public static void main(String[] args) {
int[] array = { 3, 5, 2, 8, 1, 6, 7, 9, 10};
System.out.println("Minimum value: " + min(array));
System.out.println("Sum: " + sum(array));
System.out.println("Original array: " +
getString(array));
int[] copyOfArray = copy(array);
System.out.println("Copy of array: " +
getString(copyOfArray));
int[] reverseOfArray = reverse(array);
System.out.println("Reverse of array: " +
getString(reverseOfArray));
}
}
PROGRAM OUTPUT:
csc% java Array
Minimum value: 1
Sum: 51
Original array: [3, 5, 2, 8, 1, 6, 7, 9, 10]
Copy of array: [3, 5, 2, 8, 1, 6, 7, 9, 10]
Reverse of array: [10, 9, 7, 6, 1, 8, 2, 5, 3]