這裏第一次。我的問題是,我的代碼給我一個例外邊界錯誤,我不明白爲什麼。我只需要代碼來打印相交值而不重複。感謝您的幫助,如果您需要更多信息,請詢問。2個隨機數組的交集 - Java
我不能使用任何數字,但陣列,無哈希或陣列列表。
下面是代碼:
import java.util.Random;
public class ArraySort
{
static int i,j,k,c=0;
public static void main (String [] args)
{
int [] x = new int [50];
Random generator = new Random();
System.out.println("Values in array X:");
for (int i = 0; i < x.length; i++){
x[i] = generator.nextInt(20);
// count = count + 1;
System.out.print(x[i]+" ");
}
System.out.println("");
int [] y = new int [50];
System.out.println("Values in array Y:"+" ");
for(int j =0; j < y.length; j++){
y[j] = generator.nextInt(20);
// count1 = count1 + 1;
System.out.print(y[j]+" ");
}
System.out.println("");
arrayTest(x,y);
}
public static void arrayTest (int x [] , int y[])
{
int [] z = new int [50];
// int [] b = new int [50];
for(i = 0; i < (x.length); i++)
{
for (j = 0; j <y.length; j++)
{
if (x[i] == y[j])
{
z[c]=x[i];
c++;
}
else
continue;
}
}
System.out.println("Values in array A:");
for(k =0; k < c; k++)
{
System.out.print(" "+z[k]+" ");
}
System.out.println(" ");
}
}
檢查堆棧跟蹤並告訴我們發生故障的線路。 – 2014-09-01 16:41:15
錯誤發生在z [c] = x [i];和arrayTest(x,y); – 2014-09-01 16:46:01
在該行之前,打印出c和i。一個應該很奇怪。如果可以的話,使用調試器 - 這很容易。 – 2014-09-01 17:07:14