0

I getting java.lang.IndexOutOfBoundsException in Linkedlist program to print consecutive largest and Smallest numbers in a LinkedList. example- input-

8
1 2 3 4 5 6 7 8

the output should be-

8 1 7 2 6 3 5 4
import java.util.LinkedList;
 import java.util.Scanner;
 
 class fr
 {
 public static void main(String args[])
     {
         Scanner sc=new Scanner(System.in);
         int n= sc.nextInt(),i,j,max,min,imax=0,imin=0,x;
         int size=n;
         LinkedList<Integer> arr = new LinkedList<Integer>();
         for(i=0;i<n;i++)
         {
             arr.add(sc.nextInt());
         }
         max=arr.get(0);
         min=arr.get(0);
             for(i=0;i<n;i++)
             {
                 x=arr.size();
                 for(j=0;j<x;j++)
                 {
                     if(arr.get(j)>max)
                     {
                         max=arr.get(j);
                         imax=j;
                     }
                     if(arr.get(j)<min)
                     {
                         min=arr.get(j);
                         imin=j;
                     }
                     
                 }
                 arr.remove(imax);
                 arr.remove(imin);
                 System.out.print(max+" "+min+" ");
             }
             
         }   
     }

Output window ---

8
1 2 3 4 5 6 7 8
8 1 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 6
    at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
    at java.base/java.util.LinkedList.remove(LinkedList.java:529)
    at fr.main(fr.java:36)
  • 1
    Time to learn how to use the debugger that is part of your favorite IDE. This will help you to understand where the error is occurring and the state of your key variables when the error occurs. – Hovercraft Full Of Eels Sep 13 '20 at 16:52
  • 1
    Because either `imax`or `imin` take a value that is greater than the size of the `LinkedList` or less than zero. Step through your code with a debugger or print those variables in each iteration to see where they take the incorrect value. – JustAnotherDeveloper Sep 13 '20 at 16:52
  • As you're computing your `imax` and `imin` within `if`, there are times when they are not known or correspond to indexes that are invalid outside of your `if`. You're trying to delete an element at index that might not be valid outside `for` and `if`. – dmitryro Sep 13 '20 at 17:00
  • 1
    More to the point, why are you using indexed operations on a linked list? This is certainly not the intention of the exercise. – user207421 Sep 14 '20 at 02:29

0 Answers0