【问题标题】:Nested Loop C# Visual studio [closed]嵌套循环 C# Visual Studio [关闭]
【发布时间】:2021-07-26 02:15:59
【问题描述】:

我是堆栈溢出方面的新手,基本上是 c# 编码方面的新手。我想用我将输入的行数和列数从组合框中编码一个符号。 我可以给小费吗? 例如,我希望在 label5 中显示符号“#”,行数为 5,列数为 6。

这是我的代码:

{
    for (int i = 0; i <= Convert.ToInt32(textBox1.Text); i++)
    {
        for (int k = 0; k <= Convert.ToInt32(textBox2.Text); k++)
        {
            label5.Text = comboBox1.Text + k + " ";
        }
    }
}

【问题讨论】:

    标签: c# visual-studio winforms for-loop nested-loops


    【解决方案1】:

    请看线

     label5.Text = comboBox1.Text + k + " ";
    

    分配comboBox1.Text + k + " "label5.Text,这意味着你放弃它的旧 价值并把新的。这就是为什么除了最后一个循环之外的所有循环都是徒劳的。 让我们收集所有的行。从技术上讲,你可以把

     label5.Text += comboBox1.Text + k + " ";    
    

    但是,更好的方法是

     using System.Text;
    
     ... 
    
     // We don't want constanly parse textBox1.Text, textBox2.Text; let's do it once
     int colCount = Convert.ToInt32(textBox1.Text);
     int rowCount = Convert.ToInt32(textBox2.Text);
    
     // We are going to build the string in a loop; let's do it efficiently 
     StringBuilder sb = new StringBuilder();
    
     // As I can see, you don't use i variable; 
     for (int row = 0; k <= rowCount; ++row) {
       // If we have anything, we should add a new line 
       if (sb.Length > 0)
         sb.AppendLine();
    
       // Guess: you want comboBox1.Text once in each line
       sb.Append({comboBox1.Text});
    
       // Here we create columns
       for (int col = 0; col <= colCount; ++col) {
         sb.Append($" {col} ");
     }     
    
     // Finally, we assing the text built to the label  
     label5.Text = sb.ToString();
    

    【讨论】:

    • 非常感谢您的提示和帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多