Java 99瓶啤酒挂在墙上-减法循环
我需要这首歌从99唱到0。但是当我拿到一瓶的时候,我需要把它格式化成正确的方式。我尝试使用if语句,它可以工作,但它不能使我从循环中解脱出来。循环第一次到达时,格式就被弄糟了Java 99瓶啤酒挂在墙上-减法循环,java,Java,我需要这首歌从99唱到0。但是当我拿到一瓶的时候,我需要把它格式化成正确的方式。我尝试使用if语句,它可以工作,但它不能使我从循环中解脱出来。循环第一次到达时,格式就被弄糟了 public class Example1 { public static void main(String[] args) { int counter = 99; int sum = 0; while (counter < 100 && counter > 0)
public class Example1 {
public static void main(String[] args) {
int counter = 99;
int sum = 0;
while (counter < 100 && counter > 0) {
if (counter >= 2) {
System.out.println(
counter + " bottles of Pepsi on the wall, " + counter + " bottles of Pepsi.");
System.out.println(
"Take one down, pass it around, " + (counter - 1) + " bottles of Pepsi on the wall.");
counter--;
if (counter == 1) {
System.out.println("1 bottle of Pepsi on the wall, 1 bottle of Pepsi.");
System.out.println("Take one down, pass it around, 0 bottles of Pepsi on the wall.");
counter--;
}
}
}
}
}
现在它的输出是这样的
Take one down, pass it around, 2 bottles of Pepsi on the wall.
2 bottles of Pepsi on the wall, 2 bottles of Pepsi.
Take one down, pass it around, 1 bottles of Pepsi on the wall.
1 bottle of Pepsi on the wall, 1 bottle of Pepsi.
Take one down, pass it around, 0 bottles of Pepsi on the wall.
任何帮助都将不胜感激。谢谢。如果您将制作
n瓶的代码提取到一个单独的方法中,会更容易
private static String nBottles(int n) {
return "" + n + " bottle" + (n != 1 ? "s" : "");
}
public void test(String[] args) throws Exception {
int counter = 99;
while (counter < 100 && counter > 0) {
System.out.println(nBottles(counter) + " of Pepsi on the wall, " + nBottles(counter) + " of Pepsi.");
counter--;
System.out.println("Take one down, pass it around, " + nBottles(counter) + " of Pepsi on the wall.");
}
}
私有静态字符串nBottles(int n){
返回“+n+”瓶子“+(n!=1?“s”:”);
}
公共无效测试(字符串[]args)引发异常{
int计数器=99;
同时(计数器<100&&计数器>0){
System.out.println(墙上百事可乐的“柜台”和“百事可乐的柜台”);
计数器--;
println(“拿下一个,传来传去,+n瓶子(柜台)+墙上的百事可乐”);
}
}
这不是调试的问题,更多的是你的代码没有做它应该做的事情。如果你想做If/else路由,就做一个If(counter>=3)
anelse If(counter==2)
和else
我想。你为什么不写一个接受int并返回字符串“n(s)”的助手函数呢帕特里克不知道怎么做:好主意,本,我可以试试。。谢谢,伙计,成功了,谢谢!我不知道为什么我没有想到这一点!Nit:n!=1
,而不是n>1
,因为你说的是“0瓶,1瓶,2瓶”。“瓶”和“瓶”应该是分开的字符串。不要硬编码多元化机制
private static String nBottles(int n) {
return "" + n + " bottle" + (n != 1 ? "s" : "");
}
public void test(String[] args) throws Exception {
int counter = 99;
while (counter < 100 && counter > 0) {
System.out.println(nBottles(counter) + " of Pepsi on the wall, " + nBottles(counter) + " of Pepsi.");
counter--;
System.out.println("Take one down, pass it around, " + nBottles(counter) + " of Pepsi on the wall.");
}
}