0

I'm developing a game. I'm really new in java and researched google: why does an int when added, keeps on adding java

Most of the times, it always adds even:

STOP_DAMAGE+=1;

Even sometimes, it subtract till negative. I'm annoyed. Sometimes it doesn't add too much. I do not understand. Here is my code:

if(isPressed==true) {
    if(STOP_DAMAGE<=5) {
        if(WAIT_DAMAGE>=3000) {
            ENEMY_SHIP_HEALTH-=SHIP_DAMAGE_ENEMY;
        STOP_DAMAGE+=1;
        }
    }
}
for(;WAIT_DAMAGE>=3003;) {
    WAIT_DAMAGE-=WAIT_DAMAGE;//time is deducted
}

//WAIT_DAMAGE is a time int

4

2 回答 2

1

int: int 数据类型是一个 32 位有符号二进制补码整数。它的最小值为 -2,147,483,648,最大值为 2,147,483,647(含)。对于整数值,此数据类型通常是默认选择,除非有理由(如上述)选择其他内容。这种数据类型很可能对于您的程序将使用的数字足够大,但如果您需要更广泛的值,请改用 long。

 int n =  2147483647;
 System.out.print( n+ 1);

以上会给你一个负值..

因此,一旦它达到最大值,由于位移,它从 -ve 值开始。

于 2012-10-22T11:41:39.337 回答
1

The line

 STOP_DAMAGE+=1;

always adds one unless you have an overflow, which would be surprising.

It is far more likely you need to use your debugger to get a better understanding of what your program is really doing.

BTW

for(;WAIT_DAMAGE>=3003;)
    {

        WAIT_DAMAGE-=WAIT_DAMAGE;//time is deducted
    }

is the same as

if (WAIT_DAMAGE>=3003)
    WAIT_DAMAGE = 0;
于 2012-10-22T11:38:31.543 回答