C#成神之路<11> C#循环重复语句

来源:互联网 发布:淘宝电子面单怎么申请 编辑:程序博客网 时间:2024/04/29 20:02

1、程序循环
(1)良性循环和恶性循环
良性循环的条件:
I.总是初始化循环的初始条件。
II.提供一个测试表达式来决定是否需要进行循环的下一次迭代。
III.更改控制循环变量的当前状态。

无限循环:通常是无意中产生的循环,并且会挂起系统。每当编写设计程序循环的代码,最好在运行前保存代码。

(2)for循环
在文章结尾给出本章的示例程序。
定义几个有效的变量,通过相关的代码来确保用户界面对象的输入数据的安全。
利用tryparse方法来验证输入数据是否是正确数据。

格式化字符串数据:Format()方法

  buff = string.Format("{0,5}{1,20}",i,i*i);

在平方表的程序编写中,利用了如上的代码编写,{0,5}是其第一个参数,在5个字符的字段中右对齐。
{1,20}表示第二个参数格式化为在20个字符的字段中右对齐。
以下列出相应格式选项字符串:
{0} “kate” |kate|
{0.15} “kate” | kate|
{0,-15} “kate” |kate |
{0,15:C} 5.10 | $5.10|
{0,mm}
{0,5:hh}
{0,15:hh mm}
{0,dddd MMMM}

如果字体和列不对齐,那么就是使用默认字体的原因。

 lstOutput.Items.Add(buff);

在处理字体之后,将buff中的数据添加到lstoutput中。
(3)while循环
while循环的良性三个条件仍然是在for的规则,
不过在while中限制循环的条件被分散了。

(4)do-while程序循环
其类似于while循环。只有一个不同之处:do-while至少执行一次循环语句块。

示例程序:给定一个最大值,在这个范围内生成随机数,观察需要多少次循环才能生成两个完全相同的随机数:

    private void btnStart_Click(object sender, EventArgs e)    {        bool flag;        int counter;        int max;        int last;        int current;        Random randomNumber = new Random();        flag = int.TryParse(txtMax.Text,out max);        if (flag == false)        {            MessageBox.Show("Digit characters only","Input Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);            txtMax.Focus();            return;        }        counter = 0;        last = (int)randomNumber.Next(max);        do{            current = randomNumber.Next(max);            if (last == current)            { break; }            counter++;            last = current;        }while(counter<MAXITERATIONS);        if (counter < MAXITERATIONS)        {            lblAnswer.Text = "It took " + counter.ToString() + " passes to match";        }        else {            lblAnswer.Text = "no back-to-back match";        }    }

对以上程序的简析:
这里使用符号常量MAXITERATIONS来对循环的次数进行约束。
Random的类方法next产生0~MAX-1之间的随机值。
在一个循环程序块中执行break,都会将程序控制发送给循环语句块的右侧大括号后的第一个语句。

(5)Continue循环
保持程序控制在循环中,从而判断是否授权执行下一次循环。

附加代码:平方表程序,打出一个平方表

using System;using System.Windows.Forms;public class frmMain : Form{    private Label label1;    private Label label2;    private Button btnCaculate;    private Button btnClear;    private Button btnClose;    private TextBox txtStart;    private TextBox txtEnd;    private ListBox lstOutput;    #region Windows code    private void InitializeComponent()    {            this.label1 = new System.Windows.Forms.Label();            this.label2 = new System.Windows.Forms.Label();            this.btnCaculate = new System.Windows.Forms.Button();            this.btnClear = new System.Windows.Forms.Button();            this.btnClose = new System.Windows.Forms.Button();            this.txtStart = new System.Windows.Forms.TextBox();            this.txtEnd = new System.Windows.Forms.TextBox();            this.lstOutput = new System.Windows.Forms.ListBox();            this.SuspendLayout();            //             // label1            //             this.label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;            this.label1.Location = new System.Drawing.Point(34, 33);            this.label1.Name = "label1";            this.label1.Size = new System.Drawing.Size(125, 23);            this.label1.TabIndex = 0;            this.label1.Text = "Start table value:";            this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight;            //             // label2            //             this.label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;            this.label2.Location = new System.Drawing.Point(34, 72);            this.label2.Name = "label2";            this.label2.Size = new System.Drawing.Size(125, 23);            this.label2.TabIndex = 1;            this.label2.Text = "Ending table value";            this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight;            //             // btnCaculate            //             this.btnCaculate.Location = new System.Drawing.Point(34, 115);            this.btnCaculate.Name = "btnCaculate";            this.btnCaculate.Size = new System.Drawing.Size(75, 23);            this.btnCaculate.TabIndex = 2;            this.btnCaculate.Text = "&Calculate";            this.btnCaculate.UseVisualStyleBackColor = true;            this.btnCaculate.Click += new System.EventHandler(this.btnCaculate_Click);            //             // btnClear            //             this.btnClear.Location = new System.Drawing.Point(165, 115);            this.btnClear.Name = "btnClear";            this.btnClear.Size = new System.Drawing.Size(75, 23);            this.btnClear.TabIndex = 3;            this.btnClear.Text = "&Clear";            this.btnClear.UseVisualStyleBackColor = true;            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);            //             // btnClose            //             this.btnClose.Location = new System.Drawing.Point(294, 115);            this.btnClose.Name = "btnClose";            this.btnClose.Size = new System.Drawing.Size(75, 23);            this.btnClose.TabIndex = 4;            this.btnClose.Text = "&Close";            this.btnClose.UseVisualStyleBackColor = true;            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);            //             // txtStart            //             this.txtStart.Location = new System.Drawing.Point(165, 34);            this.txtStart.Name = "txtStart";            this.txtStart.Size = new System.Drawing.Size(204, 21);            this.txtStart.TabIndex = 5;            //             // txtEnd            //             this.txtEnd.Location = new System.Drawing.Point(165, 72);            this.txtEnd.Name = "txtEnd";            this.txtEnd.Size = new System.Drawing.Size(204, 21);            this.txtEnd.TabIndex = 6;            //             // lstOutput            //             this.lstOutput.FormattingEnabled = true;            this.lstOutput.ItemHeight = 12;            this.lstOutput.Location = new System.Drawing.Point(34, 164);            this.lstOutput.Name = "lstOutput";            this.lstOutput.Size = new System.Drawing.Size(335, 148);            this.lstOutput.TabIndex = 7;            this.lstOutput.SelectedIndexChanged += new System.EventHandler(this.lstOutput_SelectedIndexChanged);            //             // frmMain            //             this.ClientSize = new System.Drawing.Size(402, 334);            this.Controls.Add(this.lstOutput);            this.Controls.Add(this.txtEnd);            this.Controls.Add(this.txtStart);            this.Controls.Add(this.btnClose);            this.Controls.Add(this.btnClear);            this.Controls.Add(this.btnCaculate);            this.Controls.Add(this.label2);            this.Controls.Add(this.label1);            this.Name = "frmMain";            this.Text = "Table of Squared";            this.ResumeLayout(false);            this.PerformLayout();    }    #endregion    //#region是C# 预处理器指令。     //#region 使您可以在使用 Visual Studio    //代码编辑器的大纲显示功能时指定可展开或折叠的代码块。    public frmMain()    {        InitializeComponent();    }    public static void Main()    {        frmMain main = new frmMain();        Application.Run(main);    }    private void lstOutput_SelectedIndexChanged(object sender, EventArgs e)    {    }    private void btnCaculate_Click(object sender, EventArgs e)    {        bool flag;        int i;        int start;        int end;        string buff;        flag = int.TryParse(txtStart.Text,out start);        if (flag == false)        {            MessageBox.Show("Numeric data only","Input error");            txtStart.Focus();            return;        }        flag = int.TryParse(txtEnd.Text,out end);        if (flag == false)        {            MessageBox.Show("Numeric data only","Input error");            txtEnd.Focus();            return;        }        if (start >= end)        {            MessageBox.Show("Start greater than end ","input error");            txtStart.Focus();            return;        }        for (i = start; i <= end; i++)        {            buff = string.Format("{0,5}{1,20}",i,i*i);            lstOutput.Items.Add(buff);        }    }    private void btnClose_Click(object sender, EventArgs e)    {        Close();    }    private void btnClear_Click(object sender, EventArgs e)    {        txtStart.Clear();        txtEnd.Clear();        lstOutput.Items.Clear();    }}
0 0