我試圖創建一個程序,該程序給出由用戶輸入創建的兩個數組的聯合,相交和差異。因此,如果用戶想要第一個數組的大小爲4,元素[1 2 3 4]和第二個數組的大小爲5並且元素[3 4 5 6 7],則輸出應該返回; A組與B組的聯合爲:1 2 3 4 5 6 7 A組與B組的交集爲:3 4 A組與B組的差值爲:1 2 此時獲得交集但是,差異不起作用。差異被打印出來作爲第一個數組的所有元素。我不知道該從哪裏開始工會。這裏是我的代碼:查找兩個單維數組的聯合,相交和差異
package rhc91310a13sets;
import java.util.*;
public class rhc91310a13sets {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] setA = null;
int[] setB = null;
System.out.print("Enter size for set A (must be less than or equal to 20): ");
setA = new int[sc.nextInt()];
System.out.print("Enter elements for set A between 1-20: ");
for (int i = 0; i < setA.length; i++) {
setA[i] = sc.nextInt();
}
System.out.print('\n');
System.out.print("Enter size for set B (must be less than or equal to 20): ");
setB = new int[sc.nextInt()];
System.out.print("Enter elements for set B between 1-20: ");
for (int i = 0; i < setB.length; i++) {
setB[i] = sc.nextInt();
}
System.out.print('\n');
System.out.print("The union of sets A and B are: ");
for(int i = 0; i < setA.length; i++) {
for(int j = 0; j < setB.length; j++) {
}
}
System.out.print('\n');
System.out.print("The intersection of sets A and B are: ");
for (int i = 0; i < setA.length; i++) {
for (int j = 0; j < setB.length; j++) {
if (setA[i] == setB[j]) {
System.out.print(setA[i] + " ");
}
}
}
System.out.print('\n');
System.out.print("The difference of sets A and B are: ");
for (int i = 0; i < setA.length; i++) {
for (int j = 0; j < setB.length; j++) {
if (!(setA[i] == setB[j]))
System.out.print(setA[i] + " ");
}
}
}
}
爲什麼不使用HashSet?然後所有這些操作都只是一個方法調用。 – 2014-09-28 01:29:44
問題是,比如'setA [0] == setB [1]','setA [0] == setB [0]'可能是錯誤的,這意味着它將被打印。您必須檢查每個元素,只有在沒有碰撞的情況下才能打印它。 – Obicere 2014-09-28 01:29:57
作業的這種氣味 – Jack 2014-09-28 03:05:54