Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most array bugs are one of a few kinds: an index outside the array, a loop that starts or stops one place off, or two names for one array mistaken for a copy. Spot them quickly, then put the whole module to work on real problems.
Mistakes and fixes at a glance
Most array bugs come from the index: where a loop starts, where it stops, or one step past the end. The commonest is off-by-one: a loop that runs one round too many or too few.
Example · Off-by-one: starting at 1 skips an element
public class SkipFirst { public static void main(String[] args) { int[] runs = {6, 12, 4}; int wrong = 0; for (int i = 1; i < runs.length; i++) { // skips runs[0] wrong += runs[i]; } int right = 0; for (int i = 0; i < runs.length; i++) { right += runs[i]; } System.out.println("Starting at 1: " + wrong); System.out.println("Starting at 0: " + right); }}Starting at 1: 16 Starting at 0: 22
What this code does
- The first loop never reads
runs[0], so the 6 runs of over 1 are missing from the total. - There is no error message, so this bug is easy to miss. Check every loop against the safe pattern: start at 0, stop with
i < a.length.
Review: Looping through an array (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
i <= a.length→ the last round crashes withArrayIndexOutOfBoundsException→ use<. Review: Reading and changing array elements (opens in a new tab)maxorminstarted at 0 → a value that is not in the array → start ata[0]. Review: Sum, average, largest and search (opens in a new tab)- Changing the for-each variable → the array stays the same → use an index loop. Review: The for-each loop (opens in a new tab)
int[] b = a;→ one array with two names →Arrays.copyOfor a loop. Review: Arrays and methods (opens in a new tab)println(a)→[I@…instead of the values →Arrays.toString(a). Review: The Arrays class (opens in a new tab)
Spot the bug
Each program below looks almost right but does the wrong thing. Read what it should do, tap the line that is wrong, then check the fix.
Before you tap, ask three questions: which indexes does it touch, is it changing the array or a copy, and are two names sharing one array?
Find the bug
Find the array bug
Select the line that is wrong.
This should print all 4 marks.
Round 1 of 6When in doubt, trace it
A program reverses an array in place, without a second array, and you want to be sure it is right. Trace it: write down the array after every step. Here two indexes walk towards each other, left from the start and right from the end, swapping as they go.
Trace the code
Reverse an array in place
Variables
- a
- {1, 2, 3, 4, 5}
Output
(nothing printed yet)Line 5Five numbers to reverse in place, without a second array.
Finish up
Mark complete & continue
Next: Must-do problems: Arrays