Rather trivial piece of Java code here.. But getting an OutOfBoundsException and I’m not quite sure why? Any help would be great!
Before anyone asks if this is homework, no it isn’t it’s for exam prep.
import java.util.Scanner;
public class exampractice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a = {1,2,3};
int min = a[0];
int max = a[0];
for (int i = 0; i <= a.length; i++){
if(a[i] < min)
min = a[i];
else
if(a[i] > max)
max = a[i];
}
System.out.println("Min is"+min+ "\nMax is: " + max);
}
}
It should be
<not<=. Zero based indices on an array vary from 0 tolength - 1.Update
Someone in grad school taught me to build up a collection of mental patterns like this and use them; you’ll avoid bugs. This one is that any array in a C-like language is always searched as
Having trained myself over the years with this, I saw this bug at, literally, first glance, which is how I got in at the head of the line.
Here’s are some more examples, for C:
But of course I should have used another pattern:
Think about what other patterns might be good.