我正在写一个函数,它返回两个整型数组之间的差异。我假设输入数组中的所有元素都是唯一的,而且输入数组也没有排序。例如:找到两个整数数组之间的差异
输入:
arr1 = [1,2,3,5,4]
arr2 = [1,2,3]
预期输出:[4,5]
我的输出:[1,2,3,4,5]
(当第一阵列比第二大)
当我使第二阵列大于第一,我得到ArrayIndexOutOfBoundsException
。
public class Test{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of first array");
int ml = sc.nextInt();
System.out.println("Enter length of second array");
int nl = sc.nextInt();
int m[] = new int[ml];
int n[] = new int[nl];
System.out.println("Enter elements of first array");
for(int i=0;i<ml;i++)
{
m[i] = sc.nextInt();
}
System.out.println("Enter elements of second array");
for(int j=0;j<nl;j++)
{
m[j] = sc.nextInt();
}
ArrayList<Integer> arr1 = new ArrayList<Integer>();
for(int i: m){ arr1.add(i);}
ArrayList<Integer> arr2 = new ArrayList<Integer>();
for(int j: n){ arr2.add(j);}
if(ml>nl)
{
arr1.removeAll(arr2);
System.out.println(arr1);
}
else
{
arr2.removeAll(arr1);
System.out.println(arr2);
}
}
}
我强烈建议你通过这个步骤与调试器。你将能够看到到底发生了什么。 –
使用try catch块进行适当的异常处理。 – Tehmina