In a task I have I need to union two sets(arrays of integers), but from some reason i'm getting the wrong output...
this is the attributes of the class set:
private int []set;
private int counter;
private int max = 10;
this is the constructor I use to get numbers(i needed to use varags because i need to be able to change the number of elements in the set):
public Set (int...numbers) {
set = new int[max];
counter = 0;
for (int i = 0; i < numbers.length; i++) {
if (!this.isMember(numbers[i])) {
this.set[this.counter] = numbers[i];
this.counter++;
}
}
}
this is the union method:
public Set union (Set setToUnion) {
Set setToReturn;
if (this.equals(setToUnion)){
setToReturn = new Set(setToUnion);
return setToReturn;
}
setToReturn = new Set(this.set);
for (int i = 0; i < setToUnion.counter; i++) {
if (!setToReturn.isMember(setToUnion.set[i])) {
setToReturn.set[setToReturn.counter ] = setToUnion.set[i];
setToReturn.counter++;
}
}
return setToReturn;
}
and if you want to see how the isMember looks so here it is(just checking if some number is a member of other set):
public boolean isMember (int n) {
if (isEmpty()) {
return false;
}
for (int i = 0; i < this.counter; i++) {
if (n == this.set[i]) {
return true;
}
}
return false;
}
Now in the program I created two sets like this:
Set someSet = new Set(1,2,3,4,5);
Set anotherSet = new Set(2,6,7,8,9);
Set m = someSet.union(anotherSet);
m.show();
but the output I'm getting is (1,2,3,4,5,0,6,7,8,9) and i need the same one but without the 0 in the middle...
please help thanks!
{}
characters in your code? In particular, the ones around the secondif
block insideunion
?