任务是,设计并实现一个应用程序,打印旅行歌曲“一百瓶啤酒”的前几节经文。使用循环,每次迭代打印一节经文。从使用中读取要打印的经文数量并验证输入。"我在遇到for循环时遇到了一些麻烦。这是我到目前为止所做的,但我很确定我已经离开了。有什么指针吗?
int verse;
int count;
System.out.println("number of verses?");
verse = scan.nextInt();
for(count= verse; count >= (verse - 3); count--)
{
System.out.println(verse + " bottles of beer on the wall");
System.out.println(verse + " bottles of beer");
System.out.println("If one of those bottles should happen to fall");
System.out.println(count + " bottles of beer on the wall");
System.out.println(count + " bottles of beer on the wall");
System.out.println(count + " bottles of beer");
System.out.println("If one of those bottles should happen to fall");
System.out.println(count + " bottles of beer on the wall");
}
答案 0 :(得分:0)
您应该在for
表达式中声明您的计数,而不是在for循环之外。你也只需要3行歌曲,因为它们会重复,直到完成循环。
for (int count = verse; count >= 3; count--) {
System.out.println(count + " bottles of beer on the wall");
System.out.println(count + " bottles of beer");
System.out.println("If one of those bottles should happen to fall");
System.out.println((count - 1) + " bottles of beer on the wall");
}
你最大的问题是你的循环中有verse
,但它并没有改变。 count
跟踪循环的当前索引,而verse
只跟踪要执行的循环数。
注意最后一行有(count - 1)
暂时显示它将减少的下一个数字。
此外,我删除了(verse - 3)
并将其替换为3
因为我认为您想要循环直到只剩下3瓶。否则请将此号码更改为1
。
答案 1 :(得分:0)
您还可以使用while
循环。
var START = 99;
var i = START + 1;
while(i--) {
System.out.println(i + " bottles of beer on the wall");
System.out.println(i + " bottles of beer");
System.out.println("If one of those bottles should happen to fall");
System.out.println(i + " bottles of beer on the wall");
}