Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod division of two integers

I keep getting the error "The operator % is undefined for the argument type(s) Integer, Integer" I am not quite sure why this is happening. I thought that since modular division cannot return decimals that having integer values would be alright.

This is happening within a method in a program I am creating. The code is as follows:

    public void addToTable(Integer key, String value)
{
    Entry<Integer, String> node = new Entry<Integer, String>(key, value);
    if(table[key % tableSize] == null)
        table[key % tableSize] = node;
}

The method is unfinished but the error occurs at

    if(table[key % tableSize] == null)

and

    table[key % tableSize] = node;

any help or suggestions would be appreciated.

like image 534
user2268305 Avatar asked Apr 25 '13 22:04

user2268305


People also ask

How do you divide modulus?

In integer division and modulus, the dividend is divided by the divisor into an integer quotient and a remainder. The integer quotient operation is referred to as integer division, and the integer remainder operation is the modulus.

How do you divide two numbers without using a division operator?

Approach: Keep subtracting the divisor from the dividend until the dividend becomes less than the divisor. The dividend becomes the remainder, and the number of times subtraction is done becomes the quotient.

What happens when you divide two integers in C++?

The / operator divides its first operand by the second. For example, 1000 / 5 evaluates to 200. If both operands are integers, the result is the integer portion of the quotient.


2 Answers

I could get some sample Integer % Integer code to compile successfully in Java 1.5 and 1.6, but not in 1.4.

public static void main(String[] args)
{
   Integer x = 10;
   Integer y = 3;
   System.out.println(x % y);
}

This is the error in 1.4:

ModTest.java:7: operator % cannot be applied to java.lang.Integer,java.lang.Integer
       System.out.println(x % y);
                            ^

The most reasonable explanation is that because Java introduced autoboxing and autounboxing in 1.5, you must be using a Java compiler from before 1.5, say, 1.4.

Solutions:

  • Upgrade to Java 1.5/1.6/1.7.
  • If you must use 1.4, use Integer.intValue() to extract the int values, on which you can use the % operator.
like image 83
rgettman Avatar answered Sep 28 '22 02:09

rgettman


This works fine for me.

Integer x = Integer.valueOf(10);
Integer y = Integer.valueOf(3);

int z = x % y;

System.out.println(z);

No problems. Output:

1

What error are you getting? What version of Java are you using? It seems that you're using Java below 1.5.

like image 38
durron597 Avatar answered Sep 28 '22 00:09

durron597