The combination of the For loop and an array is a powerful one. It lets us go through every element in order, using it's index without having to write repeated code (in fact we have already written very similar code to access the characters at any given position in a string). Example code to iterate through an array called someIntArray
is shown here:
for (int i = 0; i < someIntArray.length; i++) {
int individualItemValue = someIntArray[i];
//do something with individualItemValue
}
To use this for any other type of array just requires you to know the name of the array, and the type of contents (e.g. String, double etc.) that it contains
One use of arrays can be to perform calculations, taking an array of integers for example, we can use a variable declared outside the loop to keep a running total, as follows
int[] bankDeposits = {2999,7000,1000,35000}; //values in pence
int runningTotal = 0;
for (int i = 0; i < bankDeposits.length; i++) {
int individualDeposit = bankDeposits[i];
runningTotal += individualDeposit;
}
System.out.println("Total deposits: " + runningTotal);
In the same way we can read values in an array using a loop we could populate them - the following example code shows how prompt a user for information until an array has been populated
//array to store films
String[] fav3Films = new String[3];
//create the scanner outside the loop so it doesnt get created multiple times
java.util.Scanner inputScanner = new java.util.Scanner(System.in);
for (int i = 0; i < fav3Films.length; i++) {
System.out.println("Please type (another) favourite film");
String favFilm = inputScanner.nextLine();
fav3Films[i] = favFilm;
}