Exercise : max errors practice-it

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Returns the largest value in the given array.
public static int max(int data[10]) {
    int max = 0;
    for (int i = 0; i < data[].length(); i++) {
        if (array[i] > max) {
            max = array[i];
        }
    }
    return max[];
}

The above attempted solution to Practice-It problem "max" has 7 problems. Open Practice-It from the link above, copy/paste this code into it, and fix the errors. Complete the code so that it passes the test cases.

Exercise - answer

  1. line 2: should not write [10] after parameter name; should write [] (without length) after int
  2. line 3: starting max at 0 won't work if the array is all negative. Should initialize max variable to be data[0] and start for loop at index 1
  3. line 4: should not write [] after data here
  4. line 4: should not write () after length here
  5. line 5: array should be data
  6. line 6: array should be data
  7. line 9: should not write [] after max here

Exercise - solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Returns the largest value in the given array.
public static int max(int[] data) {
    int max = data[0];
    for (int i = 1; i < data.length; i++) {
        if (data[i] > max) {
            max = data[i];
        }
    }
    return max;
}