0

I know this error comes when we insert an element in the index which is greater than the size of an array but I still can't figure out why I am getting such an issue I have analyzed code very well but can't figure out the issue.

/*package whatever //do not write package name here */

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

class Test {
    public static void main (String[] args) {
        //code
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter T value");        
        int t = sc.nextInt();
        
        while(t > 0){
            System.out.println("Enter Array Size");
            int n = sc.nextInt();
            
            int a[] = new int[n];
            
            
            System.out.println("Enter Array Element");
            for(int i = 0;i<n; i++){
                a[i] = sc.nextInt();
            }
            
            for(int i = 0; i<n; i++){
                
            int min = i;
            
            for(int j = i; j<n;j++){
                if(a[j] < a[min]){
                    min = a[j];
                }
            }
            
            int temp = a[i];
            a[i] = a[min];
            a[min] = temp;
                
            }
            
            for(int el : a){
                System.out.print(el + " ");
            }
            
           t--; 
        }
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Azeez
  • 368
  • 2
  • 10

1 Answers1

0

Try adding 1 to n for element size. If you say 10 elements, an array will have elements 0-9. If you select item 10, that's 1 more than the size set for the array

SChavez
  • 1
  • 1
  • Sorry but I don't understand – Azeez Nov 21 '20 at 04:53
  • Try Int a[] = new int[n+1]; – SChavez Nov 21 '20 at 05:08
  • Thanks, Bro it's working but its allocate one extra garbage space what to do with that – Azeez Nov 21 '20 at 05:24
  • The problem is the prompt, when the program says "Enter Array Size" and 10 is entered, humans want to access the 10th element by entering an index of 10. Yet Java indexes 10 array elements 0 to 9. Explain to the program user that Enter array element is 1 less than maximum or explain available elements are 0 to n -1 – SChavez Nov 22 '20 at 06:51