开发者

basic java if clause question

this question is so basic that i don't even know how i could search for it...

now it's been a couple of years since i programmed but i did program for about seven years and i do distinctly remember (at least about C++) that whenever an if clause begins with e.g.:

if((x-1) &g开发者_如何学JAVAt;= 0) && ...

it simply does not matter what follows if the part left of the && is false. so how the hell could it be possible to get an array out of bounds exception for x = 0 when using "x-1" in the right part?

i never thought i would ever have to ask such a basic question... i hope i'm not overlooking something major (it is almost 4 a.m. ...) and hope somebody here can help...


Because (x-1) can be larger than 0 when x == array.length. The next condition is probably array[x], and array[ array.length ] -> OutOfBounds.

I assume you do something resembling:

if(((x-1) >= 0) && array[x] != null)

where you could have done something like:

int index = x-1;
if (index >=0 && index < array.length) {
   ...
}


i assume the misplaced paranthesis are not in your code, because the compiler would complain otherwise.

it is also possible if x is not of type int but of some unsigned type. The only unsigned type that comes to my mind is char. So if x is a char and is 0, and you subtract 1, you end up with x being 65,535 and hence lager than 0

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜