This code throws a null pointer exception at line 20, where the compareTo() is called. Any advice on how to get it to work?
package exam1review;
import java.util.Random;
public class ArrayTester {
/**
* @param args
*/
public static void main(String[] args) {
int result, max=0;
Integer[] myArray = new Integer[10];
Random rand = new Random();
for (int i = 0; i < 10; i++) {
myArray[i] = rand.nextInt();
System.out.println(myArray[i]);
while (i != myArray.length - 1) {
result = myArray[i].compareTo(myArray[i+1]);
if (result > 0)
max = myArray[i];
else
max = myArray[i+1];
}
}
System.out.println(max);
}
}
the problem is that you’re looping over
i, but your comparison tries to compare tomyArray[i+1]before it’s set.Populate the array first, then look for the max value.
Like this: