This content has been marked as final. Show 4 replies
You increment b to 1 in the beginning of your code. You're dividing by 1, not 0.
I've a question about 0 divident exception.
I wrote the following code, where c, d, and e should have triggered 0 divident exceptions, but in fact no exception happend. Why?
Because a 'divide by zero' exception only occurs when you attempt to 'divide by zero'.
This line of code sets 'b' to zero
And this line of code increments 'b' to 1
nt b = 0;
So these lines of code are dividing by 1
Dividing by 1 does not cause a 'divide by zero' exception.
int c = a / b; int d = a/b; int e=(a/b);
after I change my code as following, when I executed it, the 0 divident exception did happened. I don't knowd why.
Because this line of code sets 'b' to 0
Anid this line of code tries to divide by 0
int b = 0;
Because a 'divide by zero' exception occurs when you attempt to 'divide by zero'.
int c = a / b;
For the Java spec for the postfix operator (++) see the Java Language Specification
15.14.2. Postfix Increment Operator ++
. . .
the value 1 is added to the value of the variable and the sum is stored back into the variable.
. . .
General Tip: Invest a few hours in learning to use a debugger. All IDE's come with them. Stepping through the code in a debugger & watching variable values change will make the answers to questions like this immediately obvious.
Without a debugger, you have to track variable values mentally, and if you're like me, you'll invariably overlook something, especially as the code grows more complex.
Debuggers are great if you want to like them (which some people do not for some reason), but the OP was already using the "spam system out" trick to not have to remember variable state. You don't -have- to use a debugger, sometimes its just easier to let the code print out what its doing and then examine that. Less mouse clicking that way :)