我仍在學習Java的基礎知識,並且在正確使用for循環邏輯時遇到問題。我目前正在創建一個打印「Beer Bottle」歌曲的節目。我的代碼正常運行並且完整,但是我的邏輯有缺陷。我已經爲此循環了好幾天了,我仍然不確定它應該是什麼樣子。嘗試在java中編寫for循環,但找不到正確的邏輯
該計劃的目標是提示用戶他們想要打印多少首「啤酒瓶」歌曲。如果用戶輸入2,那麼下面應該出現:
100 bottles of beer on the wall
100 bottles of beer
If one of those bottles should happen to fall
99 bottles of beer on the wall
99 bottles of beer on the wall
99 bottles of beer
If one of those bottles should happen to fall
98 bottles of beer on the wall
我的代碼如下所示:
import java.util.Scanner;
public class BottleSong
{
public static void main (String [] args)
{
printBottleSongVerses();
}
public static void printBottleSongVerses()
{
int versesToPrint;
int verseNumber;
int state;
state = 0;
versesToPrint = 0;
verseNumber = 0;
String checkInt;
checkInt = null;
Scanner scan = new Scanner (System.in);
System.out.println ("This program prints verses of the 'One Hundred Bottles of Beer' song.");
System.out.println ("How many verses would you like to read?");
if (scan.hasNextInt())
{
versesToPrint = scan.nextInt();
state = 1;
}
else System.out.println("Error! This program only accepts integer values!");
if (state == 1)
{
if (versesToPrint <= 100)
{
for (; versesToPrint > 0 ; versesToPrint--)
{
verseNumber = 101 - versesToPrint;
System.out.println (verseNumber + " bottles of beer on the wall");
System.out.println (verseNumber + " bottles of beer");
System.out.println ("If one of those bottles should happen to fall");
System.out.println (verseNumber - 1 + " bottles of beer on the wall");
}
}
}
}
}
現在我知道書中有一些不必要的代碼,但那是因爲我一直玩了一會兒。它的工作原理,但它反過來打印的經文。如果3是輸入,則控制檯打印98,然後是99然後是100.我需要它以另一種方式打印。任何人都可以幫助解決我的邏輯?
你可能會嘗試一個小的改變;使用經文打印來計算經文的數量,就像你擁有它。然後在我們的循環之外(在for循環之前)執行「verseNumber = 101」,並將表示verseNumber = 101 ...的行更改爲「verseNumber--」。因此,for循環計算要經過的經文的數量,而經文數量每次迭代下降一個。 – user1676075