Reputation: 1491
I have made a class called Iset
that takes integers and modifies it's boolean array's index equivalent to the integer to true.
e.g. If I pass an integer 1 then the boolean array setI[1]
is turned to true.
I have a method called include
that returns true if the provided integer is in there and false if it isn't. However no matter what I do I always get true
. I have made sure that everything in the array is set to false and I add in a number further up the code. Obviously I'm missing something really obvious here:
public class Iset {
public int size;
boolean[] setI;
Iset(int a) {
this.size = a;
this.setI = new boolean[size];
}
public boolean include(int i) {
for (int n = 0; n <= size; n++) {
if (setI[n]== setI[i]){
return true;
}
}
return false;
}
}
Upvotes: 0
Views: 144
Reputation: 1519
The other answers have given solutions, but I think we can also get an explanation going as to why your original code was slightly wrong as you say. Here is what your include() method is doing in pseudocode:
for each boolean called 'setI[n]' in the array:
if 'setI[n]' is the same as the boolean at 'setI[i]':
return true
So, it's not actually checking if either of those boolean are true or false, it's just checking if they are the same. This method will always return true unless the boolean at index i
is the only one in the array with its value (I'd suggest trying that to see if I am right). For example, if i = 1
your method will return true
for:
[false, true, false, false, ...]
[true, false, true, true, ...]
... and no other values.
Hopefully this makes things a little clearer.
Upvotes: 3
Reputation: 5508
Please try this code, I think you should add a funktion: set(), and change a little of the include(int i)
public class Iset {
public int size;
boolean[] setI;
Iset(int a) {
this.size = a;
this.setI = new boolean[size];
}
public boolean include(int i) {
return setI[i];
}
//set your values in the boolean array "setI" to "true"
public void set(int... values) {
for (int i : values) {
setI[i] = true;
}
}
public static void main(String[] args) {
Iset mm = new Iset(100);
mm.set(25, 40, 22);
System.out.println(mm.include(25));
}
}
Upvotes: 3
Reputation: 7994
You don't have to walk over the complete array, just ask the method if your number is included.
public boolean isIncluded(int i) {
if (setI[i] == true){
return true;
}
return false;
}
or even simpler:
public boolean isIncluded(int i) {
return setI[i];
}
P.S. I changed your method name to something more meaningful
Upvotes: 2
Reputation: 26
I'm not completely sure what you are after for, but, in you for-loop you are making a selfcomparison when n == i
and thus return true always.
Upvotes: 0
Reputation: 7804
Try this:
public boolean include(int i) {
if (i >= size){
// To avoid ArrayIndexOutOfBoundsException
return false;
}
return setI[i];
}
Upvotes: 0