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.
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.
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.
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.
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:
Integer.intValue()
to extract the int
values, on which you can use the %
operator.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With