这是我用 Java 编写的第二个脚本,因为我刚刚开始写一本关于它的书,所以我为这个不可避免的荒谬问题道歉。
我正在编写一个脚本来唱“墙上的 99 瓶啤酒”,并尝试在循环内的条件中声明一个新的 String 变量。不幸的是,它不会编译,因为该字符串据说是未声明的。然后,当我将它从条件中拉出但仍在循环中时,它运行良好。我在这里错过了什么吗?
在职的:
while (beersLeft >= 0) {
String sOrNot = "";
if (beersLeft > 1) {
sOrNot = "s";
} else {
sOrNot = "";
}
System.out.println(beersLeft+" bottle"+sOrNot+" of beer on the wall, "+beersLeft+" bottle"+sOrNot+" of beer!");
System.out.println("Take one down, pass it around, "+beersLeft+" bottle"+sOrNot+" of beer on the wall!");
System.out.println();
beersLeft = beersLeft-1;
}
不工作
while (beersLeft >= 0) {
if (beersLeft > 1) {
String sOrNot = "s";
} else {
String sOrNot = "";
}
System.out.println(beersLeft+" bottle"+sOrNot+" of beer on the wall, "+beersLeft+" bottle"+sOrNot+" of beer!");
System.out.println("Take one down, pass it around, "+beersLeft+" bottle"+sOrNot+" of beer on the wall!");
System.out.println();
beersLeft = beersLeft-1;
}
错误:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at ch01.BottlesOfBeer.main(BottlesOfBeer.java:21)