Reputation: 191
I find a very weird situation when writing Java code:
Integer x = myit.next();
if ((int)x % 2 == 0) {
In which myit is an Iterator and x is an Integer. I just want to test whether x is an even number or not. But x % 2 == 0 does not work since eclipse says % not defined on Integer. Then I try to convert x to int by explicitly converting. Again, it warns me that not able to convert in this way.
Any reason why it happened and what is the right way to test if x is even ?
UPDATE: ANYWAY,I test it that the following code works, which means all of you guys are right.
Integer x = 12;
boolean y = ( (x % 2) == 0 );
boolean z = ( (x.intValue() % 2) == 0 );
I think the problem I have before may be the context of the code. It is late night, I would update later if I find why would that thing happen.
Upvotes: 2
Views: 2169
Reputation: 36304
Use :
if (x.intValue() % 2 == 0)
PS : if(x % 2==0)
should also work because integer.intValue()
should be called internally.
Byte code for :if(x % 2==0)
11: invokevirtual #23; //Method java/lang/Integer.intValue:()I --> line of interest
14: iconst_2
15: irem
Upvotes: 5
Reputation: 35557
x % 2 == 0 does not work since eclipse says % not defined on Integer
This is not true. You can use %
with Integer
take a look at this
Integer x = new Integer("6");
if (x % 2 == 0) {
System.out.println(x);
}
Out put:
6
You should read about Integer in Java
Upvotes: 2
Reputation: 26067
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(21);
myList.add(22);
myList.add(41);
myList.add(2);
Iterator<Integer> itr = myList.iterator();
while (itr.hasNext()) {
Integer x = itr.next();
if (x % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
Output
odd
even
odd
even
Upvotes: 1