Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This method is supposed to have a loop and return a string. How do I do that? This what I have so far. I'm new to C#.

public string BLoop()
{
    for (int i = 99; i > 0; i--)
    {
        Console.WriteLine(string.Format("{0} bottles of beer on the wall, {0}   bottles of beer.", i));
        Console.WriteLine(string.Format("Take one down, pass it around, {1} bottles of beer on the wall.", i, i - 1));
        Console.WriteLine();
    }
}

++ I tried all the thing you suggested but I think I should rephrase the method is supposed to return a string that is printed by the main.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm assuming you need to return the string constructed in your loop (and not just some arbitrary string as in the other answers). You need to build a string instead of just writing the strings out, then return that string:

public string BLoop()
{
    var builder = new StringBuilder();
    for (int i = 99; i > 0; i--)
    {
        builder.AppendLine(string.Format("{0} bottles of beer on the wall, {0} bottles of beer.", i));
        builder.AppendLine(string.Format("Take one down, pass it around, {0} bottles of beer on the wall.", i-1));
    }

    return builder.ToString();
}

Note that I've also amended the second line of your loop to eliminate the redundant String.Format parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...