我一直在获取ArrayIndexOutOfBoundsException。我试图调整所有数组的大小并跟踪了我的代码,但似乎没有弹出来!
我正在比较arr和brr之间的数字。我正在尝试打印出在brr中而不是在arr中的数字,以及重复频率不如在brr中的数字。
我将这些数字放入一个单独的数组中并打印出来。我也尝试使用Lists来做到这一点,但是我得到了相同的异常。
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];
}
}
答案 0 :(得分:0)
问题是您要遍历用户输入的数组brr
。这意味着您假设输入<=200。您需要将这些数组的大小设置为输入n
和m
。希望这会有所帮助!