试图在java中编写for循环,但无法弄清楚正确的逻辑

时间:2014-03-05 12:39:49

标签: java for-loop

我还在学习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.我需要它打印另一种方式。任何人都可以帮助修复我的逻辑吗?

2 个答案:

答案 0 :(得分:1)

您可以略微改变方法,只需在经文数量周围写下循环,然后更改墙上的瓶子数量。

int numberOfBottles = 100;
if (versesToPrint <= 100)
{   
    for (int i = 0; i < versesToPrint; i++)
    {
    System.out.println (numberOfBottles + " bottles of beer on the wall");
    System.out.println (numberOfBottles + " bottles of beer");
    System.out.println ("If one of those bottles should happen to fall"); 
    System.out.println (numberOfBottles - 1  + " bottles of beer on the wall");
    numberOfBottles--;
    }
}

答案 1 :(得分:0)

使用循环变量:

for (int verseNumber = 100; verseNumber > 100 - versesToPrint; verseNumber--)