【发布时间】:2018-01-07 18:18:30
【问题描述】:
我正在编写一个函数,它返回两个整数数组之间的差异。我假设输入数组中的所有元素都是唯一的,并且输入数组也没有排序。例如:
输入: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 块进行适当的异常处理。