2015-02-09 61 views
0

的下列值低于在Java int的范围错误

long Count = 2151685171 
int CurrentPosition = 849 
int employeesLeft = 1276 

代码引发indexOutOfBound错误:

int EmployeeToBeEliminated = (int)(count+currentPosition-1)%employeesLeft; 

而如果这样写的

count = (count+currentPosition-1)%employeesLeft; 
int EmployeeToBeEliminated = (int)count; 

没有错误抛出。但在第一种情况下,取模后的数值减小到01276的范围,所以应该很容易铸造成int。那么为什么它会抛出一个错误?

+0

检查整数。MAX_INT和自动装箱:在第一种情况下,所有值都会转换为int,而在第二种情况下,所有值都会转换为long。 – terjekid 2015-02-09 08:22:16

+0

您包含的代码不会抛出IndexOutOfBoundsException。你可能有一些代码,你使用'EmployeeToBeEliminated'作为一些Collection /数组的索引。 – Eran 2015-02-09 08:22:35

+1

你的变量在你的代码中被称为'Count',但是你使用'count'。 'currentPosition'相同。 – emlai 2015-02-09 08:22:35

回答

1

countlongint的范围之外的值。

一个强制转换被应用于(在本例中为括号)操作数的右边。你能想象剧组括号像下面这样:

((int)(count+currentPosition-1)) %employeesLeft 

铸造的(count+currentPosition-1)int引起溢出的结果。

你想要的是:

(int)((count+currentPosition-1)%employeesLeft) 
0

它首先投射

(count+currentPosition-1) 

为int,打破约束int的+2.147.483.647,然后尝试取模。

尝试:

int EmployeeToBeEliminated = (int)((count+currentPosition-1)%employeesLeft); 
+0

它是一个int,但是因为它将long转换为int(对于int而言它的值太大,所以转换使其为负值)。当你通过积极模糊否定的结果是否定的 – 2015-02-09 08:27:11

0

这是Java运算符优先级的问题。

在第一代码示例中,代码被按照该顺序进行处理:

  1. (int)(count+currentPosition-1)
  2. Result from 1 %employeesLeft;

在第二代码示例中,代码被按照该顺序进行处理:

  1. (count+currentPosition-1)%employeesLeft;
  2. (int) Result from 1

要得到相同的结果,第一个代码示例应写为:

int EmployeeToBeEliminated = (int)((count+currentPosition-1)%employeesLeft);

注意新的括弧中加入。

参考文献:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html