简体   繁体   中英

Convert Integer to int in Java

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.

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
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

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

Use this:

if(((int)x)%2==0){

Note: one more (

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM