简体   繁体   中英

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException:

So my assignment is write a recursive Java method that finds the maximum of an array of integers without using any loops. The input is a first line that contains a single integer n < 10. The next line contains n numbers separated by spaces. The output should be a single integer. Call your program FindMax. The below code is what I have so far, it compiles but instead of me being able to enter

input line 1: 5 (n) } 

This is what I need to be able to input

input line2: 2 3 4 5 3 }

it makes me enter

input: 5 (n)
input: 2
input: 3
input: 4
input: 5
input: 3

also after entering the above I get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at FindMaxtesting.getmax(FindMaxtesting.java:35)
at FindMaxtesting.getmax(FindMaxtesting.java:48)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.getmax(FindMaxtesting.java:42)
at FindMaxtesting.main(FindMaxtesting.java:17)

This is my code so far:

import java.util.Scanner;

public class FindMaxtesting
{
   public static void main (String[]args)
   {
  Scanner sc = new Scanner(System.in);
  int n = sc.nextInt(); 
  int i = 0;
  int fin = 0;
  System.out.println(getmax( Inca(n ) , n , fin , i));
   }

   public static int[] Inca(int n )
   {
  Scanner sc = new Scanner(System.in);
  int[] arr = new int[n];
  for(int j=0;j<n;++j)
  {
     arr[j] = sc.nextInt();
      }
      return arr;   
   }    

   public static int getmax ( int arr[], int n, int fin, int i )
   {
      int temp = 0;
      if (fin < arr[i])
      {
         temp = fin;
     fin = arr[i];
     arr[i] = temp;
     i++;
     getmax(arr , n , fin , i);
      }

      else if (fin > arr[i])
      {
         i++;
     getmax(arr , n , fin , i);
      }

      else if ( i == n-1 )
      {
         return fin;
      }
      return fin;
   }
}

The essence of your problem is that in getmax you need to add the lines

if (i >= n)
    return fin;

You are searching through the array recursively, which isn't really the best way to do it, but I assume that this is a homework problem, and you need to say when to stop looking further through the array, however you continue to look further in the array. When i>=n then you know you have searched the entire array, and can just return fin, as there are no further values that can be greater.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM