The compiler doesn't look at the result, it looks at the type. The type of m%3
is long
, and you are trying to put it into an int
.
So, the compiler is angry, because potentially, the value stored in a long
is bigger than the one you can store into an int
.
In order to remove the problem, you have to cast the result back into an int
:
A[i] = (int) (m % 3);
However, you can do this because you know the result is 0,1 or 2. If you do not know the value of the long
you are casting, you may have an integer overflow:
public static void main(String[] args) {
long l = Integer.MAX_VALUE + 1L;
System.out.println(l);
// 2147483648
System.out.println((int)l);
// -2147483648
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…