Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

this is my java code to return largest element from given array but it is showing indexoutofbound exception.please help

0 votes
asked Aug 13, 2018 by anonymous
import java.util.Arrays;

import java.util.Scanner;

public class LargestElement

{

public static void main(String[] args)

{

int f=0;

//fill your code here

int a1[]=new int[20];

for(int i=0;i<6;i++)

{

a1[i]=Integer.parseInt(args[i]);

}

f= checkLargestAmongCorner(a1);

System.out.println(f);

}

public static int checkLargestAmongCorner(int []a)

{

//fill your code here

int large=0;

int max=a[0];

if (a[1]>a[max]&&a[1]>a[Math.round(max/2)])

{

large = a[1];

}

else if(a[Math.round(max/2)]>a[1]&&a[Math.round(max/2)]>a[max])

{

large=a[Math.round(max/2)];

}

else if (a[max]>a[1]&&a[max]>a[Math.round(max/2)])

{

large=a[max];

}

return large;

}

}

1 Answer

0 votes
answered Oct 12, 2018 by anonymous
The int variable "max" used in checkLargestAmongCorner represents the content of a[0], and does NOT represent the address of any element of a. Depending on the contents of a, this will definitely trigger an "index out of bounds" exception.

You should seriously read up on loops. Loops come into play when you want to process each element of an array. In this case, obviously you want to look at each element of the array to determine the largest element that the array contains.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...