Skip to content
Advertisement

Java skips some of my code after for loop

I am trying to get the union of two sets but for some reason my code has no errors but my method for getting the union skips some of the code

    public Set union(Set s){
    Set union = new Set(count+s.count);

    for(int x=0;x<count;x++)
        union.set[x] = set[x];

    for(int y=count;y<s.count;y++){
        union.set[y] = s.set[y];
    }
    return union;
}

The program works but the problem is after the first loop it skips the rest of the code inside the method.

Here’s the rest of my code that might be related to the problem

public class Set implements InterfaceSet{
private int set[];
private int count;

public Set(){
        set = new int[max];
        count = 0;
    }

public Set(int size){
    set = new int[size];
    count = size;
}

private int found;
public void add(int e){
    found = 0;
    if(count<10){
        for(int x: set){
            if(x==e){
                found=1;
                break;
            }
        }
        if(found==0){
            set[count] = e;
            count++;
        }
    }
}

public void display( ){
    for(int x=0;x < count; x++){
        System.out.println(set[x]);
    }
}

Advertisement

Answer

Your union methods seems incorrect. Could you try this?

public Set union(Set s){
    Set union = new Set(count + s.count);

    for(int x = 0; x < count; x++)
        union.set[x] = set[x];

    // updated
    for(int y = 0; y < s.count; y++){
        union.set[count + y] = s.set[y];
    }

    return union;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement