Why does my application break when I remove the null
check?
The first thing to note is this: The Netbeans warning is wrong.
By removing the null
check around rest();
you are changing the flow of the first run of your do while
loop. Importantly, you are allowing rest()
to be called. The net effect of this is that hunger
is now larger than it normally would be had you left the null
check in place.
What's now happening is this:
- First loop iteration begins:
hunger = 4, level = 3
rest()
is called:hunger
increments to5
.findCat()
is called:hunger
increments to6
,"1.Ginger"
is returned.huntCat(1)
is called:hunger
increments to7
.1 < 3
(catLevel < level
) evaluates totrue
, causinghunger
to be decremented by4
(so we're now at3
).hunger
is not greater than5
, so continue to the next iteration.- Second loop iteration begins:
hunger = 3, level = 3
rest()
is called,hunger
increments to4
.findCat()
is called,hunger
increments to5
,"3.Porkchops"
is returned.huntCat(3)
is called,hunger
increments to6
3 < 3
(catLevel < level
) evaluates tofalse
,hunger
does not get decremented.hunger
is greater than5
, soRuntimeException("x_x")
is thrown.
How can I fix this?
Well, given that the Netbeans warning is wrong (because catLevel
definitely is null
in the first iteration), the simplest solution is just to reinstate your null
check and ignore the warning.
If you wish, you can disable the warning by clicking the lightbulb next to the warning on the left side, browsing the menus, and choosing "Disable warning". Though personally I would rather put up with one aggravating yellow underline if it lead to better quality code in the long run.
Alternatively, increase level
to 4
, or decrease hunger
to 3
, or change your if
statement to check if hunger > 6
instead.