Reputation: 41
Incompatible type found java.util.vector required HighRights. Sorry I am new to Java and I just don't understand how to do this question
Notice: in this exercises we will NOT use Generics
In the following program, the code in the method CountHighs
is missing.
Write the code for this method, which takes as argument the vector m and
returns the number of objects in the vector that are instances of HighRights
The method should also:
- check that the elements extracted from the vector are indeed instances
of the classes HighRights
or LowRights
. If an element is not an instance of such classes,
then the method should return -1.
handle the NullPointerException
in case the vector is null. Use the following
code when catching the occurring exception:
System.out.println("Error");
System.exit(0);
return 0;
(Hint:
m.size()
to get the number of elements in the vector minstanceof
to check if an object is an instance of a class)For example,
HighRights
objects and one LowRights
objects then CountHighs(m)
will return 2HighRights
objects and one String
objects then CountHighs(m)
will return -1LowRights
objects no HighRights
objects then CountHighs(m)
will return 0Any help/tips will be appreciated. Thank you very much.
Upvotes: 0
Views: 64
Reputation: 172
You should post full code (not as image) and the error stack trace, but I think I know the problem. You have a public static int CountHighs(Vector m)
method, and inside it you check condition m instanceof HighRights/LowRights
- it's never true, a Vector is a Vector, not HighRights. You need to check if objects stored in the vector are HighRights or LowRights. To do this, you should use a loop:
for(Object obj : m){ //it will iterate over the vector `m`, with each iteration `obj` will be the next element
if(obj instanceof HighRights){
++countHighRights;
}
else if(obj instanceof LowRights){
//do nothing - you should only count HighRights
}
else{ //obj is neither HighRight nor LowRight
return -1;
}
}
Upvotes: 1