-1

in this code the Arraybound Exception occurred in b[x][0]=a[i]; i run this code for one test case it is properly but for more than one it give run time error please help me to find correct solution and uderstanding of this code in this code i take a static variable x for count for a number how many time repeat that's all

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

class GFG {
    static int x=0;
    public static void main (String[] args) {
    Scanner sc= new Scanner(System.in);
    int t = sc.nextInt();
    while(t-->0){
       int n = sc.nextInt();
       int a[] =new int [n];
        for ( int l=0;l<n;l++){
            a[l]=sc.nextInt();
        }
        int b[][]=new int [n][2];
        a= sort(a);
        b  = sort(b);
        frequency(b,a);
        printArray(b);
    }
    }
    
        //System.out.println(" ");
    public static void printArray(int b[][]){
            for ( int i =0;i<x;i++){
            for ( int j =0;j<=b[i][1];j++){
              System.out.print(b[i][0]+" ");
            }
        }
    }
public static void frequency(int b[][],int a[]){
        b[x][0]=a[0];
        for ( int i =1;i<a.length;i++){
            if (a[i]==a[i-1]){
                b[x][1]=b[x][1]+1;
            }
            else{
                x++;
                b[x][0]=a[i];
            }
        }
         x++;
}
    public static int [][]sort (int b[][]){
        int c[] = new int[2];
        for (int i =0;i<x;i++)
        {
            for (int j =i;j<x;j++){
                if(b[i][1]<b[j][1]){
                    c=b[i];
                    b[i]=b[j];
                    b[j]=c;
                }
            }
        }
        return b;
    }
    public static int [] sort(int a[]){
        for (int i =0;i<a.length;i++){
            for (int j =i;j<a.length;j++){
                if (a[i]>a[j]){
                int temp = a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    return a;
    }}
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Progman May 28 '22 at 11:50

0 Answers0