我正在寫一個函數,它返回兩個整型數組之間的差異。我假設輸入數組中的所有元素都是唯一的,而且輸入數組也沒有排序。例如:找到兩個整數數組之間的差異
輸入:
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