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

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

loops - c# Method to return a string?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...