I keep getting ArrayIndexOutOfBoundsException. I tried to resize all the arrays and traced my code but nothing seems to pop up to me!
I am comparing the numbers between arr and brr. I am trying to print out the numbers that are in brr but not arr and the numbers that are repeated less often than in brr.
I am putting these numbers in sperate array and printing it out. I also tried to do it using Lists but im getting the same Exception.
public class Solution {
static int[] array = new int[200];
static int nextIndex = 0;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter n: ");
int n = s.nextInt();
System.out.println("enter numbers in arr: ");
//List<Integer> arr = new ArrayList<>();
int arr[];
arr = new int[200];
for (int i=0; i<n ; i++){
arr[i] = s.nextInt();
}
System.out.println("enter m: ");
int m = s.nextInt();
//List<Integer> brr = new ArrayList<>();
int brr[];
brr = new int[200];
System.out.println("enter numbers in brr: ");
for (int i=0; i<m ; i++){
brr[i] = s.nextInt();
}
//System.out.println("The missing nums are : ");
//List<Integer> finalArray;
//ArrayList<Integer> finalArray;
int finalArray[];
finalArray = new int[200];
finalArray = missingNums(arr,brr);
for (int i =0; i<finalArray.length; i++){
System.out.println(finalArray[i]);
}
}
public static int[] missingNums(int arr[], int brr[]){
int oFreq = 1, fFreq = 0;
int num, num2=-1;
for (int i=0; i<brr.length; i++){
num = brr[i];
//finding the frequency for each num in brr at a time
for (int j=0; j< brr.length; j++)
if (brr[j + 1] == num) {
oFreq++;
//System.out.println(oFreq);
}
//checking if the same num exists in arr and storing it in num2
for (int x = 0; x<arr.length; x++){
if (arr[x] == num)
num2 = arr[x];
else
push(num);
//nums.add(num);
}
//if the same number as in brr exists in arr find its frequency in arr
if (num2 != -1){
//find frequency of the number in arr
for (int x = 0; x<arr.length; x++){
if (num2 == arr[x])
fFreq++;
}
}
if (oFreq > fFreq)
push(num);
}
return (array);
}
public static void push(int e) {
array[nextIndex] = e;
++nextIndex;
}
public static int pop() {
--nextIndex;
return array[nextIndex];
}
}