0

Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.

package com.programs.interview;
import java.util.Scanner;

public class FindMaxNumInArray {

public static void main (String[] args) 
{ 
    Scanner scan = new Scanner (System.in); 
    System.out.print("Enter the size of the array: "); 
    int arraySize = scan.nextInt(); 
    int[] myArray = new int[arraySize]; 
    System.out.print("Enter the " + arraySize + " values of the array: "); 
    for (int i = 0; i < arraySize; i++)
        myArray[i] = scan.nextInt(); 
    for (int j = 0; j < arraySize; j++) 
        System.out.println(myArray[j]); 
    System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + "."); 
} 

public static int maximum(int[] arr, int Arraylength){
    int tmp;
    if (Arraylength == 0)
        return arr[Arraylength];
    tmp = maximum(arr, Arraylength -1);
    if (arr[Arraylength] > tmp)
        return arr[Arraylength];
    return tmp;
  }
}

Output

Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3 4 5 1 2 3 4 5 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26) at com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)

6
  • 1
    The Console Gives me this out put: Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3 4 5 1 2 3 4 5 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26) at com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17) Commented Feb 22, 2014 at 21:33
  • 1
    Yes, because an array with 5 elements does not have a element index [5]. Only 0 1 2 3 4 Commented Feb 22, 2014 at 21:34
  • Does it have to be recursive? Using a loop would be simpler, and faster. Commented Feb 22, 2014 at 21:35
  • So ...? I mean is there problem in initializing the array with 5 ? Commented Feb 22, 2014 at 21:36
  • Actually m new in programming, and i was interviewed with recursive method. Commented Feb 22, 2014 at 21:38

5 Answers 5

3

This is the problem:

if (arr[Arraylength] > tmp)

Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.

It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.

EDIT: If you really want how I would write the recursive form, it would be something like this:

/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
    if (array.length == 0) {
        // You need to decide what to do here... throw an exception,
        // return some constant, whatever.
    }
    // Okay, so the length will definitely be at least 1...
    return maximumRecursive(array, array.length);
}

/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
    // We know that upperBoundExclusive cannot be lower than 1, due to the
    // way that this is called. You could add a precondition if you really
    // wanted.
    if (upperBoundExclusive == 1) {
        return array[0];
    }
    int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
    int topValue = array[upperBoundExclusive - 1];
    return Math.max(topValue, earlierMax);

    // Or if you don't want to use Math.max
    // return earlierMax > topValue ? earlierMax : topValue;
}
Sign up to request clarification or add additional context in comments.

8 Comments

You mean this would help : public static int maximum(int[] arr, int Arraylength){ int tmp; if (Arraylength == 0) return arr[Arraylength]; tmp = maximum(arr, Arraylength-1); if (arr[Arraylength-1] > tmp) return arr[Arraylength]; return tmp; }
@AliAnsari: No, that will still fail - you're still returning arr[Arraylength], and if the array is empty then you're still going to try to take the first element from it. Again, you really need to decide what you want to do if the length of the array is 0.
Thnx Alot: it worked now: public static int maximum(int[] arr, int Arraylength){ int tmp; if (Arraylength == 0) return arr[Arraylength]; tmp = maximum(arr, Arraylength-1); if (arr[Arraylength-1] > tmp) return arr[Arraylength-1]; return tmp; }
@AliAnsari: Well that's still not going to work if the array is empty, but other than that it's okay. It's not how I would write the code, mind you - I'd use iteration rather than recursion.
M also convenient with iterative solution, but my need was recursive. Kindly , can u re-write it as if you will have to write it. I need to compare that one with mine to clear that where am i mistaken.
|
2

you can't access

arr[Arraylength]

the last element would be at

arr[Arraylength -1]

for example if you have

int arr[] = new int[5];

then the elements would be at 4, because index starts from 0

arr[0], arr[1], arr[2], arr[3], arr[4]

1 Comment

Thnx alot for explaining
0

Your issue is in the following piece of code:

if (arr[Arraylength] > tmp)
            return arr[Arraylength];

Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].

Comments

0

I would use a plain loop. Java doesn't do recursion particularly well.

public static int maximum(int[] arr) {
    int max = Integer.MIN_VALUE;
    for(int i : arr) if (i > max) max = i;
    return max;
}

1 Comment

Actually m new in programming, and i was interviewed with recursive method.
0

here

System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");

you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.