Ex:
arrayA: 3 5 8 9
arrayB: 3 4 6 9
difference of A-B: 5 8
however, my code is just returning me an array of 0's
im trying to use my search method (which has been tested and works) to take a number from the first array and search it in the other array. If it is not found the search method returns a 0 and the number from the first array is then stored into the 3rd array.
here is the portion of my code, I'm not sure what is wrong.
Expand|Select|Wrap|Line Numbers
- //Cory Boughton
- import java.util.*;
- public class Sets {
- public static Scanner kbd = new Scanner (System.in);
- public static final int MAXSIZE = 20;
- public static void main(String[] args) {
- int[]setA = new int[MAXSIZE];
- int[]setB = new int[MAXSIZE];
- int[]intersect = new int [MAXSIZE];
- int[]difference = new int [MAXSIZE];
- int sizeA, sizeB, interSize, diffSize;
- System.out.print("How many numbers will be in the 1st set: ");
- sizeA = kbd.nextInt();
- while (sizeA > MAXSIZE){
- System.out.print("Error: Set size is too large. Re-enter set size: ");
- sizeA = kbd.nextInt();
- }
- System.out.println("Enter list of integers for 1st set: ");
- getData(setA, sizeA);
- System.out.print("How many numbers will be in the 2nd set: ");
- sizeB = kbd.nextInt();
- while (sizeB > MAXSIZE){
- System.out.print("Error: Set size is too large. Re-enter set size: ");
- sizeB = kbd.nextInt();
- }
- System.out.println("Enter list of integers for 2nd set: ");
- getData(setB, sizeB);
- interSize = intersection(setA, sizeA, setB, sizeB, intersect);
- System.out.print("The intersection of the two sets is: ");
- for (int x = 0; x < interSize; x++){
- System.out.print(intersect[x] + " ");
- }
- diffSize = difference(setA, sizeA, setB, sizeB, intersect);
- System.out.print("\n\nThe difference of A-B is: ");
- for (int x = 0; x < diffSize; x++){
- System.out.print(difference[x] + " ");
- }
- }
- public static void getData(int[]set, int size){
- for(int x = 0; x < size; x++){
- int num = kbd.nextInt();
- int count = search(set, size, num);
- if (count == 0)
- set[x] = num;
- else
- x--;
- }
- }
- public static int search(int[]set, int size, int num){
- int count = 0;
- for (int x = 0; x < size; x++){
- if (num == set[x])
- count++;
- }
- return count;
- }
- public static int difference(int[]setA, int sizeA, int[]setB, int sizeB, int[]resultSet){
- int y = 0;
- for (int x = 0; x < sizeA; x++){
- int num = setA[x];
- int found = search(setB, sizeB, num);
- if (found == 0){
- resultSet[y] = num;
- y++;
- }
- }
- return y;
- }
- }