0
package Prac;

import java.io.*;
import java.util.*;

public class Practice {

    public static void main(String [] args){
        int[] test = {0,1,2,99,4,5};

        int maximum = max(test);
        System.out.print(maximum);
    }

    public static int max(int[] test1){
        int max =0;
        for(int i = 0; i <=test1.length;i++){
            if(test1[i]>=max){
                max=test1[i];
            }
        }   
        return max;
    }
}

// Java doesn't show an errors until I run this program and it gives me:

//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:     6
//at Prac.Practice.max(Practice.java:18)
//at Prac.Practice.main(Practice.java:9)

// I am supposed to write a method that takes an array of ints as a parameter and returns the largest element of the array.

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
  • How many elements does your array contains and how many indexes exist between `0` and `test1.length` (both inclusive since you used `=0` and `<=test1.length`)? – Pshemo Dec 13 '15 at 21:55
  • You may want to initialize `max` as `int max = test1[0];`. You can then start the loop with `int i = 1` since `max` is holding the value at position 0. This way the method still works as intended if it is given an array of negative numbers (since 0 is obviously greater than all negative numbers). Changing `<=test1.length` to ` – Calvin P. Dec 13 '15 at 22:10

0 Answers0