简体   繁体   中英

How to continue from the break in a for loop

string[] sentence = new string[] { "I like C++.", "I like C#.", "I like Java." };

for (int i = 0; i < sentence.Length; i++)
{
    for (int j = 0; j < sentence.Length; j++)
    {
        richTextBox1.Text += sentence[j] + "\n";
        break;
    }
}

Is it possible to continue the inner loop from where it stops so I can get the output of:

I like C++.
I like C#.
I like Java.

做这个:

richTextBox1.Text = string.Join("\n", sentence );

The break keyword will always "break-out" of the current block of code. In this case, it is your inner for-loop.

I think you looking for the continue keyword.

Try simply below:

string[] sentence = new string[] { "I like C++.", "I like C#.", "I like Java." };

for (int i = 0; i < sentence.Length; i++)
{
        richTextBox1.Text += sentence[j] + "\n";
}
string[] sentence = new string[] { "I like C++.", "I like C#.", "I like Java." };

            for (int i = 0; i < sentence.Length; i++)
            {
                xyz:

                for (int j = i; j < sentence.Length; j++)
                {
                    richTextBox1.Text += sentence[j] + "\n";
                    break;
                }

                 i++;
                 if (i == sentence.Length) { break; }
                 goto xyz;
            }
string[] sentence = new string[] { "I like C++.", "I like C#.", "I like Java." };

for (int i = 0; i < sentence.Length; i++)
{
    for (int j = **i**; j < sentence.Length; j++)
    {
        richTextBox1.Text += sentence[j] + "\n";
        break;
    }
}

Instead of int j = 0, make it as int j = i in the second loop.. Though there are better solutions to "THIS" problem, I assume you are looking at a different set of problems to check if such continuation is possible.

Maybe you do not want to end of the line after the last item? Then:

string[] sentence = new string[] { "I like C++.", "I like C#.", "I like Java." };

for (int i = 0; i < sentence.Length; i++) {
    richTextBox1.Text += sentence[j];
    if(i < sentence.Length-1)
        richTextBox1.Text += "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM