Learn Java · lesson 27 of 61 · about 8 minutes
Looping over Arrays
Add up the week's ticket sales: fill an array with a for loop, total it with for-each, and print it with Arrays.toString.
What you'll learn
- Loop with an index
- Loop with for-each
- Sort, print and fill with Arrays
The week's sales
The desk keeps how many tickets were sold on each of the last 7 days. They're typed in, oldest first, into new int[7] with a for loop, because each one needs its index. Adding them up only needs each value, so a for-each loop does that and finds the best day too. Arrays.toString prints the whole week in one go.
Two kinds of loop
for (int i = 0; i < a.length; i++)gives you the indexfor (int x : a)(for-each) gives you each item, without an index
java.util.Arrays has helpers: Arrays.sort(a), Arrays.toString(a) for printing, Arrays.fill(a, v).
Total, maximum and sorting
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] temps = {12, 17, 9, 21, 15};
int total = 0;
int max = temps[0];
for (int t : temps) {
total += t;
if (t > max) max = t;
}
System.out.printf("Total %d, average %.1f, max %d%n", total, (double) total / temps.length, max);
Arrays.sort(temps);
System.out.println(Arrays.toString(temps));
}
}Output
Total 74, average 14.8, max 21
[9, 12, 15, 17, 21]Tip
Printing an array directly shows something like [I@1b6d3586. Use Arrays.toString(a) to see the values.
Tip
Arrays lives in java.util, like Scanner, so it needs its own import: import java.util.Arrays;
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.