我有以下简单的代码来模拟猫狩猎:
import java.util.Arrays;
import java.util.LinkedList;
public class HuntigSaeson {
int hunger = 4;
int level = 3;
LinkedList<String> cats = new LinkedList<String>(Arrays.asList(
"1.Ginger",
"3.Porkchops",
"2.Muffin",
"2.Max",
"1.Carrot",
"2.Puffy",
"1.Fatty"
));
void hunt() {
Integer catLevel = null;
do {
if (catLevel != null)
rest();
catLevel = new Integer(findCat().split("\\.")[0]);
huntCat(catLevel);
if (hunger > 5) throw new RuntimeException("x_x");
} while (hunger > 0);
System.out.println("^_^");
}
void rest() { hunger += 1; }
String findCat() {
hunger += 1;
String c = cats.pop();
System.out.println("found " + c);
return c;
}
private void huntCat(int catLevel) {
hunger += 1;
if (catLevel < level) {
System.out.println("chomp chomp chomp");
hunger -= 4;
}
}
public static void main(String[] args) { new HuntigSaeson().hunt(); }
}
它产生以下输出:
found 1.Ginger
chomp chomp chomp
found 3.Porkchops
found 2.Muffin
chomp chomp chomp
found 2.Max
chomp chomp chomp
found 1.Carrot
chomp chomp chomp
found 2.Puffy
chomp chomp chomp
found 1.Fatty
chomp chomp chomp
^_^
空比较行的目的是我不想在狩猎第一只猫之前休息。 Netbeans 突出显示了该行,并表示我应该将其删除。
所以我这样做,通过改变
if (catLevel != null)
rest();
to
rest();
但现在我死了:
found 1.Ginger
chomp chomp chomp
found 3.Porkchops
Exception in thread "main" java.lang.RuntimeException: x_x
at HuntigSaeson.hunt(HuntigSaeson.java:24)
at HuntigSaeson.main(HuntigSaeson.java:46)
为什么?我怎样才能解决这个问题?
为什么当我删除应用程序时我的应用程序会崩溃null
check?
首先要注意的是:Netbeans 警告是错误的.
通过删除null
检查一下rest();
you are改变你的第一次运行的流程do while
环形。重要的是,您允许rest()
被称为。这样做的最终效果是hunger
现在比你离开时通常要大null
检查到位。
现在发生的事情是这样的:
-
第一个循环迭代开始:
hunger = 4, level = 3
-
rest()
叫做:hunger
增加到5
.
-
findCat()
叫做:hunger
增加到6
, "1.Ginger"
被返回。
-
huntCat(1)
叫做:hunger
增加到7
.
-
1 < 3
(catLevel < level
) 评估为true
,导致hunger
递减4
(所以我们现在处于3
).
-
hunger
不大于5
,因此继续下一次迭代。
-
第二次循环迭代开始:
hunger = 3, level = 3
-
rest()
叫做,hunger
增加到4
.
-
findCat()
叫做,hunger
增加到5
, "3.Porkchops"
被返回。
-
huntCat(3)
叫做,hunger
增加到6
-
3 < 3
(catLevel < level
) 评估为false
, hunger
不会减少.
-
hunger
大于5
, so RuntimeException("x_x")
被抛出。
我怎样才能解决这个问题?
好吧,鉴于 Netbeans 警告是错误的(因为catLevel
绝对是 null
在第一次迭代中),最简单的解决方案就是恢复您的null
检查并忽略警告。
如果你希望,您可以通过单击左侧警告旁边的灯泡、浏览菜单并选择“禁用警告”来禁用警告。但就我个人而言,如果从长远来看它能带来更好的代码质量,我宁愿忍受一个令人恼火的黄色下划线。
或者,增加level
to 4
,或减少hunger
to 3
,或者改变你的if
语句来检查是否hunger > 6
反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)