



版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
相关程序设计ー、实现ー个Window窗体应用程序,可以实现画圆、计算、画五环与填充颜色的功能代码部分创建一个新类,名叫DrawPic.csusingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;namespaceCaseOl{classDrawPic(#region属性〃字段坐标值privateintx;publicintX(get{returnx;}set{if(value<=0||value>=300)x=150;elsex=value;))privateinty;publicintY(get{returny;}set(if(value<100||value>130)y=100;elsey=value;})〃字段宽高privateintp_width;publicintP_widthget{returnp_wi出h;}setif(value<=10||value>=380)p_width-200;elsep_width=value;})privateintp_height;publicintP_height(get{returnp_height;}set(if(value<=10||value>=160)
p_height=200;elsep_height=value;))//结构颜色Colorc_color;constdoublepi=3.14F;#endregion#region构造函数publicDrawPic()()III<summary>///指定坐标和寛高///</summary>III<paramname="x">x坐标值</param>III<paramname="y">y坐标值</param>III<paramname="pwidth">宽度</param>III<paramnameゴpheighf'>咼度</param>publicDrawPic(stringX,stringY,stringP_width,stringP_height)(this.X=int.Parse(X);this.Y=int.Parse(Y);this.P_width=int.Parse(P_width);this.P_height=int.Parse(P_height);)III<summary>Ill指定坐标和宽高构造函数重载III</summary>///<paramname="x">x坐标值</param>///<paramname="y">y坐标值</param>///<paramnameゴpwi出h">宽度</param>III<paramname="pheighf'>咼度</param>///<paramnameゴcolors”>颜色</param>publicDrawPic(stringX,stringY,stringP_width,stringP_height,Colorcolors)(this.X=int.Parse(X);this.Y=int.Parse(Y);this.P_width=int.Parse(P_width);this.P_height=int.Parse(P_height);this.c_color=colors;)#endregionIII<summary>III实现画圆III</summary>III<paramnameゴf">所需画圆的窗体</param>publicvoidDrawCircle(System.Windows.Forms.Formf)〃在窗体上绘制ー个画图图面(画布)Graphicsg=f.CreateGraphics();〃创造ー个画笔指定画笔颜色及画笔宽度Penpen=newPen(Color.Black,3);//指定画出的图形质量使用消除锯齿g.SmoothingModeSystem.Drawing.Drawing2D.SmoothingMode.AntiAlias;//使用画笔画圆g.DrawEllipse(pen,newRectangle(x,y,p_width,p_height));//释放画布g.Dispose();//释放画笔pen.Dispose();)publicvoidFillColor(System.Windows.Forms.Formf)(Graphicsg=f.CreateGraphics();Penpen=newPen(Color.Black,3);g.SmoothingModeSystem.Drawing.Drawing2D.SmoothingMode.AntiAlias;g.lnterpolationModeSystem.Drawing.Drawing2D.lnterpolationMode.High;〃定义ー个使用颜色的填充对象Brushb=newSolidBrush(c_color);//填充一个形状在固定的坐标上g.FillEllipse(b,x+1.5F,y+1.5F,p_height-3,p_wi出h-3);g.Dispose();pen.Dispose();)publicstringgetResult(intd)(doublec=pi*d;doubles=pi*((d/2)*(d/2));returnstring.Format("当前圆的周长是{0:F2},面积是{1:F2}!",c,s);)))二、关于属性的使用创建一^Window窗体应用程序例子:学生年龄输入合法性的判断(成功实现)1、关于Form1.cs查看代码可得:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespaceCase02(publicpartialclassForml:Form(publicForml()(lnitializeComponent();)privatevoidbtnMsg_Click(objectsender,EventArgse)(studentmyStudent=newstudent();myStudent.Age=int.Parse(txtAge.Text.Trim());MessageBox.Show(string.Format("年龄是:{0}",myStudent.Age.ToString()),"显示年龄",MessageBoxButtons.OK,MessageBoxIcon.Information);//myStudent.Name="zane";//stringgrade=myStudent.Grade;}privatevoidbtnNo_Click(objectsender,EventArgse){MessageBox.Show("该用户的今年、t"+txtAge.Text+"\T 岁","显示年龄",MessageBoxButtons.OK,MessageBoxIcon.Information);)))2、添加类student.esusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceCase02(classstudentprivateintage;publicintAgeget{returnage;}set(if(value>0&&value<110)(age=value;)else{age=18;)))privatestringname;III<summary>III只读///</summary>publicstringNameget{returnname;})privatestringgrade;III<summary>III只写III</summary>publicstringGrade(set{grade=value;})}}三、参数的值传递(使用ref与。ut进行)自定义计算税后エ资事例:エ资计税的方法为:低于等于3500不计税,超出3500的部分按10%缴税查看form.cs的代码加以编写usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespaceCase03(publicpartialclassForml:Form(publicForml()(lnitializeComponent();}privatevoidbtnAccount_Click(objectsender,EventArgse)(intpay=int.Parse(txtPay.Text.Trim());doubleresult=0.00F;getResult(refpay,outresult);MessageBox.Show(string.Format("您的工资总额是:{0}\n超出起征点{1:F2}元'n应缴纳{2:F2}元个人所得税",txtPay.Text.Trim(),pay,result), "税率计算",MessageBoxButtons.OK,MessageBoxIcon.Information);privatevoidgetResult(refintpay,outdoubleresult)pay-=3500;if(pay<1500)(result=0.00F;)elseif(pay>=1500&&pay<4500)(result=pay*0.1F;)elseif(pay>=4500&&pay<9000)(result=pay*0.2F;)elseif(pay>=9000&&pay<35000)(result=pay*0.25F;)elseif(pay>=35000&&pay<55000)result=pay*0.3F;)elseif(pay>=55000&&pay<80000)(result=pay*0.35F;)else(result=pay*0.45F;))))四、构造函数的使用应先添加Window窗体,代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespaceCase04publicpartialclassMainForm:Form(publicMainForm(){lnitializeComponent();)privatevoidbtnExit_Click(objectsender,EventArgse)(this.Close();)privatevoidbtnTestStudentClass_Click(objectsender,EventArgse)(//Studentzhang=newStudent();//zhang.Name="张靓靓";//zhang.Age=20;//zhang.Hobby="唱歌歌";Studentscofield=newStudent("Scofield",28,"越狱狱)Studentzhang=newStudent("张靓靓、20,"唱歌歌");Studentjay=newStudent("周杰杰",21,"耍双节棍棍");//Studentscofield=newStudent("Scofield");scofield.SayHi();zhang.SayHi();jay.SayHi();)})事例:学生的自我介绍,代码如下:Student.cs代码usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Windows.Forms;namespaceCase04classStudentpublicStudent(){}publicStudent(stringname)(this.Name=name;)publicStudent(stringname,intage,stringhobby)(this.Name=name;this.Age=age;this.Hobby=hobby;)///<summary>III姓名III</summary>privatestringname;publicstringNameget{returnname;}set{name=value;}Ill<summary>///年龄///</summary>privateintage;publicintAge{get{returnage;}set(〃属性是聪明的字段if(value>0&&value<100)(age=value;)else(age=18;)))///<summary>//Z爱好Ill</summary>privatestringhobby;publicstringHobby(get{returnhobby;}set{hobby=value;})publicvoidSayHi()(stringmessage;message=string.Format("大家好,我是{0}同学,今年{1}岁了,我喜欢{2}〇",name,this.age,this.hobby);MessageBox.Show(message);)))五、应先添加Windows图体(MainForm.es査看代码并进行编辑)使用构造函数实例化1、StriictStudent.cs的代码如下usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Windows.Forms;namespaceCaseStruct{publicenumGenders(Male,Female)〃结构版StudentstructStructStudent(publicstringName;publicGendersGender;publicintAge;publicstringHobby;publicintPopularity;publicStructStudent(stringname,Gendersgender,intage,stringhobby):this(name,gender,age,hobby,100){}publicStructStudent(stringname,Gendersgender,intage,stringhobby,intpopularity)(this.Name=name;this.Gender=gender;this.Age=age;this.Hobby=hobby;this.Popularity=popularity;)publicvoidSayHi()(stringmessage;message=string.Format("大家好,我是{0}同学,今年{1}岁了,我喜欢{2}。我的人气值高达{3}!",this.Name,this.Age,this.Hobby,this.Popularity);MessageBox.Show(message);)))2、MainForm.es代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespaceCaseStruct(publicpartialclassMainForm:Form{publicMainForm()(lnitializeComponent();)privatevoidbtnExit_Click(objectsender,EventArgse)(this.Close();)privatevoidbtnTest_Click(objectsender,EventArgse)〃不使用new//TestStruct();//使用newTestStructNew();)privatevoidTestStruct()(StructStudentmyStu;myStu.Age=20;myStu.Gender=Genders.Female;myStu.Hobby="唱歌歌";myStu.Name="张靓靓";myStu.Popularity=100;myStu.SayHi();)privatevoidTestStructNew()(StructStudentmyStu=newStructStudent("张靓靓",Genders.Female,20,"唱歌歌",100);myStu.SayHi();)六、mySchoo!类使用索引器知识点1、MainForm.cs的代码入下:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespaceMySchool{publicpartialclassMainForm:Form(publicMainForm()(lnitializeComponent();)privatevoidbtnExit_Click(objectsender,EventArgse)
this.Close();)//测试入口privatevoidbtnTestStudentClass_Click(objectsender,EventArgse)(//TestValueReference();TestArrayParameter();//Testindexer();)//值类型和引用类型参数演示privatevoidTestValueReference()(〃传递引用类型参数Studentscofield=newStudentf'Scofield",Genders.Male,28,”越狱狱う;scofield.SayHi();Vote(refscofield);scofield.SayHi();////传递值类型参数//StructStudentscofieldnew//StructStudentscofieldnewStructStudentf'Scofield",Genders.Male,28,”越狱狱ケ//scofield.SayHi();//Vote(refscofield);//scofield.SayHi();)//数组参数演示privatevoidTestArrayParameter()(int[]odd={1,3,5};PrintArray(odd);ChangeToEven(odd);PrintArray(odd);)〃索引器演示privatestaticvoidTestindexer()(////采用数组属性的方式//MyClasslmyClassl=newMyClass1("T01");//myClassl.Students[2].SayHi();〃〃myClass1.Students[”周杰杰"].SayHi();〃编译出〃采用索引器的方式MyClassmyClass=newMyClass("T01");myClass.Students[2].SayHi();myClass.Students「周杰杰”].SayHi();)//投票每次投票增加人气值1privatevoidVote(refStudentstu)(stu.Popularity++;)//投票每次投票增加人气值1privatevoidVote(refStructStudentstu)(stu.Popularity++;)privatevoidChangeToEven(int[]arr)(for(inti=0;i<arr.Length;i++)(arr[i]=i*2;})privatevoidPrintArray(int[]arr)for(inti=0;i<arr.Length;i++)Console.WriteLine("arr[{0}]={1i,arr[i]);))})2、MyClass.esusingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceMySchool(III<summary>III班级类///</summary>classMyClasspublicMyClass(stringname)=name;this.students=newStudents();)〃班级名称privatestringname;publicstringName(get{returnname;}set{name=value;}}〃学员集合privateStudentsstudents;internalStudentsStudentsget{returnstudents;}set{students=value;}3、MyClassl.csusingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceMySchool(classMyClassl(publicMyClassl(stringname)(=name;this.students=newStudent[3];students[O]=newStudent("Scofield",Genders.Male,28,"越狱狱ッ;students[1]=newStudent("张靓靓",Genders.Female,20,"唱歌歌”);students[2]=newStudent("周杰杰",Genders.Male,21,"耍双节棍棍");)〃班级名称privatestringname;publicstringNameget{returnname;}set{name=value;})//学员集合privateStudentQstudents;publicStudent[]Students(get{returnstudents;}set{students=value;})))4、StructStudent.esusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Windows.Forms;namespaceMySchool{〃结构版StudentstructStructStudentpublicstringName;publicGendersGender;publicintAge;publicstringHobby;publicintPopularity;publicStructStudent(stringname,Gendersgender,intage,stringhobby):this(name,gender,age,hobby,100){}publicStructStudent(stringname,Gendersgender,intage,stringhobby,intpopularity)(this.Name=name;this.Gender=gender;this.Age=age;this.Hobby=hobby;this.Popularity=popularity;)publicvoidSayHi()stringmessage;message=string.FormatC,大家好,我是{0}同学,今年{1}岁了,我喜欢{2}。我的人气值高达{3}this.Name,this.Age,this.Hobby,this.Popularity);MessageBox.Show(message);))}5、Student.esusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Windows.Forms;namespaceMySchool{publicenumGenders(Male,Female}〃类版StudentclassStudentpublicStudent。:this("张靓靓",Genders.Female,20,“唱歌歌",100){}publicStudent(stringname):this(name,Genders.Male,20,"打篮球",10〇){}publicStudent(stringname,Gendersgender,intage,stringhobby):this(name,gender,age,hobby,100){}publicStudent(stringname,Gendersgender,intage,stringhobby,intpopularity)this.Name=name;this.Gender=gender;this.Age=age;this.Hobby=hobby;this.Popularity=popularity;III<summary>III姓名III</summary>privatestringname;publicstringNameget{returnname;}set{name=value;})III<summary>///性别///</summary>privateGendersgender;publicGendersGender(get{returngender;}set{gender=value;})///<summary>III年龄///</summary>privateintage;publicintAge(get{returnage;}set(〃属性是聪明的字段if(value>0&&value<100)age=value;)else{age=18;)))〃人气指数privateintpopularity;publicintPopularity(get{returnpopularity;}set{popularity=value;})III<summary>//Z爱好///</summary>privatestringhobby;get{returnhobby;}set{hobby=value;})publicvoidSayHi()(stringmessage;message=string.Format("大家好,我是{0}同学,今年{1}岁了,我喜欢{2}。我的人气值高达{3}!'*,,this.age,this.hobby,this.popularity);MessageBox.Show(message);}})6、Students.esusingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceMySchoolclassStudentsprivateStudentQstudents=newStudent[3];publicStudents()(students[O]=newStudent("Scofield",Genders.Male,28,"越狱狱ッstudents[1]=newStudent("张靓靓",Genders.Female,20,"唱歌歌");students[2]=newStudent("周杰杰",Genders.Male,21,"耍双节棍棍");)//基本索引器根据数组下标查找学员publicStudentthis[intindex](get{returnstudents[index];})〃〃与Java中的getter方法类比证明方法可以返回一个类型//publicStudentGetStudent(intindex)//{//returnstudents[index];//)〃重载的索引器根据姓名查找学员publicStudentthis[stringname](get(inti;boolfound=false;for(i=0;i<students.Length;i++)(if(students[i].Name==name)(found=true;break;))if(found)(returnstudents[i];}elsereturnnull;))))七、string的相关应用事例:stringMethod 发送电子邮件的相关代码1、CheckMail.csusingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Net;usingSystem.Net.Mail;namespacestringMethod{classCheckMailpublicboolCheck(stringemail)if(!string.lsNullOrEmpty(email))if(email.lndexOf("@")==-1){System.Windows.Forms.MessageBox.ShowC'T^^^S,您输入的电子邮件格式不正确","输入提示");returnfalse;)else{returntrue;))else(System.Windows.Forms.MessageBox.Show("对不起,您必须输入电子邮件","输入提示");returnfalse;})///<summary>Ill获取用户邮箱服务器地址III</summary>///<paramname="email"></param>III<returns></returns>publicstringGetMailAddress(stringemail){string[]s_mail=email.Split('@');if(string.Equals(s_mail[1],"163.com") ||string.Equals(s_mail[1],"126.com")||string.Equals(s_mail[1],""))(return"";}elseif(string.Equals(s_mail[1],""))(return"";)elseif(string.Equals(s_mail[1],"188.com"))(return"";}elseif(string.Equals(s_mail[1],"263.net") ||string.Equals(s_mail[1],"263.")||string.Equals(s_mail[1],""))(return"";)elseif(string.Equals(s_mail[1],"")||string.Equals(s_mail[1],""))(return"/";}elseif(string.Equals(s_mail[1],""))(return"";)elseif(string.Equals(s_mail[1],"")||string.Equals(s_mail[1],"")||string.Equals(s_mail[1],""))(return"/cgi-bin/loginpage";}elseif(string.Equals(s_mail[1],"")||string.Equals(s_mail[1],""))return"";)else(return"http://mail."+s_mail[1].ToString();})///<summary>II!发送邮件基础类III</summary>III<paramname="mailAdd">由B件目标地址</param>III<paramname="title">邮件标题</param>III<paramname="bodys">由B件主体</param>publicvoidsetMails(stringmailAdd,stringtitle,stringbodys)(MailMessagemails=newMailMessage();mails.From=newMailAddress("\"邮件发送测试\"admin@");〃邮件来源地址"\"德和木业网\"muyew@dohigh.cc"mails.To.Add(newMailAddress(mailAdd));〃邮件目标mails.Subject=title;〃邮件标题mails.Body=bodysJ 〃邮件主体mails.Priority=MailPriority.High;//使用最高邮件优先级mails.IsBodyHtml=true;〃使用Html格式的邮件mails.BodyEncoding=System.Text.Encoding.GetEncoding("GB2312");//设置邮件主体编码格式SmtpCIient sc = newSmtpClient("");//sc.Credentials = newNetworkCredential("admin@", "mujie-hr");//admin@mujie2009的(sc.Send(mails);)catch(Exceptionex){throwex;}2、Formi,csusingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespacestringMethod{publicpartialclassFormi:Form(publicFormi()(lnitializeComponent();)privatevoidbtnSet_Click(objectsender,EventArgse)CheckMailcm=newCheckMail();if(cm.Check(textBox1.Text.Trim()))try{cm.setMails(textBox1.Text.Trim(),”发送邮件测试","这是测试邮件");System.Diagnostics.Process.Start("lExplore.exe",cm.GetMailAddress(textBox1.Text.Trim()));string[]str=textBox1.TextTrim().Split('@');MessageBox.Show(string.Format。嘟件发送成功!邮件用户名是:{0},邮件地址为:{1}",str[0].ToString(),string.Join("@",str)),"发送邮件",MessageBoxButtons.OK,MessageBoxIcon.Information);)catch(Exceptionex)(MessageBox.Show("对不起,消息发送失败,可能的失败原因是:"+ex.Message,"发送失败",MessageBoxButtons.OK,MessageBoxIcon.Error);})ハ、简易计算器usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespace简易计算器1(classProgram(staticvoidMain(string[]args)(inti,j;stringoper="+";Console.WriteLine("简易计算器V1.0");Console.WriteLine();Console.WriteLine("请输入第一个数:");Console.Write("»");i=newProgram().vallnput();Console.WriteLine("请输入第二个数:");Console.Write("»");j=newProgram().vallnput();Console.WriteLine("计算结果是:");Console.WriteLine(newProgram().(oper,i,j));}privateintvallnput(){try(returnint.Parse(Console.ReadLine());}catch(Console.WMteLine("对不起,您输入的数字格式不正确,请重新输入!");Console.Write("»");returnvallnput();))privatestringfghf(stringoper,inti,intj)(stringstr;switch(str)casestr=Convert.ToString(i+j);break;casestr=Convert.ToString(i-j);break;casestr=Convert.ToString(i*j);break;casestr=Convert.ToString(i/j);break;default:Console.WriteLine("对不起,您输入的数字格式不正确!");break;})))九、刚开始的程序练习usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationlstaticvoidMain(string[]args)(Console.WriteLine("HelloWorld");)})十、打开程序后出现的代码usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationl(classProgramstaticvoidMain(string[]args))十ー、变・相关(两个变・赋值后输出)(—)usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationl{classProgram(staticvoidMain(string[]args)(Console.WriteLine("HelloWorld");intmyAge,yourAge;myAge=31;yourAge=21;Console.WriteLine("我今年{〇}岁,你们今年{1}岁。",myAge,yourAge);〃占位符)})(二)usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationl(classProgram(staticvoidMain(string[]args)(Console.WriteLine("HelloWorld");intmyAge.yourAge;myAge=31;yourAge=21;strings="我小";Console.WriteLine("我今年{〇}岁,你们今年{1}岁。{2}",myAge,yourAge.s);〃占位符)))十二、隐式转换usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationlstaticvoidMain(string[]args)(Console.WriteLine("对不起,您还好吧?〇;Console.Write("»");inti=int.Parse(Console.ReadLine());Console.WriteLine(i);}//类型转换string转换为整形))十三、十四、输入两名学生的信息(两种方法)自己完成的程序usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationlclassProgramstaticvoidMain(string[]args)stringname1=Console.ReadLine();intage1=int.Parse(Console.ReadLine());stringname2=Console.ReadLine();intage2=int.Parse(Console.ReadLine());Console.WriteLine("工作人员A的姓名是:"+name1);Console.WriteLine("工作人员A的年龄是:"+age1);Console.WriteLine("工作人员A的姓名是:"+name2);Console.WriteLine("工作人员A的年龄是:"+age2);))}老师的程序(使用了“+”以及占位符)usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceConsoleApplicationlstaticvoidMain(string[]args)(stringage1,namel,age2,name2;Console.WriteLine("请输入第一位学员的年龄:");Console.Write("»");age1=Console.ReadLine();Console.WriteLine("请输入第一位学员的姓名:");Console.Write("»");namel=Console.ReadLine();Console.WriteLine("请输入第二位学员的年龄:");Console.Write("»");age2=Console.ReadLine();Console.WriteLine("请输入第二位学员的姓名:");Console.Write("»");name2=Console.ReadLine();Console.WriteLine(" ");Console.WriteLine("第一名学员是"+name1+",他今年是"+age1+"岁"レ/方法一:使用"+"Console.WriteLine("第二名学员是{0},他今年{1}岁",name2,age2);〃方法二:使用占位符Console.WriteLine();〃相当于换行))十五、异常处理1、使用try...catch块捕获和处理异常try(intnum=int.Parse(Console.ReadLine());//……)catch(处理的异常类型)(/Z错误处理代码)finally块——无论是否发生异常,都会执行try(intnum=int.Parse(Console.ReadLine());//)catch(处理的异常类型))finally}2、checked语句块中的任何整数运算溢出,都会抛出ー个OverflowException笄常unhecked语句块中的任何整数运算都不会被强制检查溢出,永远不会抛出OverflowException异常intnumber=lnt32.MaxValue;checked{intw川Throw=number++;Console.WriteLine(“强制检查))uncheckedintwontThrow=number++;Console.WriteLine("强制不检查溢出”);注意:不能使用checked和unchecked控制浮点(非整数)运算。只能控制整数运算。3、使用异常处理学员信息录入usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacetryCatch(classProgram(staticvoidMain(string[]args)(stringnamel,name2;intage1,age2;newProgram。.Print("请输入第一位学员的姓名:");namel=newProgram().Read();newProgram。.Print("请输入第一位学员的年龄:");age1=newProgram().checkRead();newProgram。.Print("请输入第二位学员的姓名:");name2=newProgram。.Read。;newProgram。.Print("请输入第二位学员的年龄:");age2=newProgram().checkRead();newProgram().Print(name1,name2,age1,age2);)privatevoidPrint(stringstr)(Console.WriteLine(str);Console.Write("»");)privatevoidPrint(stringnamel,stringname2,intage1,intage2)(Console.WriteLine("第一位学员的姓名是:"+namel+",他今年"+age1+"岁");Console.WriteLine("第二位学院的姓名是:{0},他今年{1}岁",name2,age2);Console.ReadLine();)privatestringRead()returnConsole.ReadLineQ;)privateintcheckRead()(try(returnint.Parse(Read());}catch(Exceptionex)(newProgram。.Print("对不起,您的输入有误请重新输入:");returncheckRead();})))十六、在控制台打印出图案(9行9列:staticvoidMain(string[]args)(inti,j;〃循环变量for(i=1;i<=9;i++) //外层循环控制行数for(j=1;j<=9;j++)//内层循环控制每行打印的Console.Write("*\t");)Console.WriteLine();/Z换行)Console.ReadLine();)十七、break和continue用在二重循环中:跳出本层循环,继续执行外层循环for(...){for(...)break;)跳出本次循环,继续下一次循环for(...)continue;)十八、5个专卖店促销,每个专卖店每人限购3件衣服,可以隨时选择离开,离店时要结账for(i=0;i<5;i++)/Z每次进ー个专卖店(fora=0;j<3;j++)/Z每个店限购3件if(离开这家店)break;)选购一件衣服)结账)usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello{III<summary>///本示例演示如何在内层循环使用breakIII</summary>classProgram(staticvoidMain(string[]args)(intcount=0;〃计算共卖了多少件衣服inti,j;〃循环变量stringchoice;/Z顾客的选择是否离开〃外层循环控制依次进入下一个专卖店for(i=0;i<5;i++)(Console.WriteLine("\n欢迎光临第{〇}家专卖店for0=0;j<3;j++){Console.WMte("要离开吗(y/n)?");choice=Console.ReadLine();//如果离开,就跳出,结账,进入下ー个店if(choice=="y")break;Console.WriteLine("买了一件衣服");count++;/Z买一件衣服)Console.WriteLine("离店结账ッ;}Console.WriteLine("\n共买了{0}件衣服",count);Console.ReadLine();)for(i=0;i<5;i++)〃外层循环控制依次进入下一个专卖店(Console.WriteLine("\n欢迎光临第{0}家专卖店”,i+1);for(j=0;j<3;j++)〃内层循环ー次买一件衣服(Console.Write("要离开吗?y/n");choice=Console.ReadLine();if(choice=="y")//如果离开,就跳出,结账,进入下ー个店(break;)Console.WriteLine("买了一件衣服");count++;/Z买一件衣服)Console.WriteLine("离店结账う;)十九、平均分某次程序大赛,3个班级各4名学员参赛,计算每个班参赛学员的平均分共3个班级,循环3次计算每个班的平均分每班4名学员,循环4次累加总分需要使用二重循环实现for、while、do-while、foreach语句可以相互嵌套usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello(III<summary>II!此程序演示内层循环continue应用///</summary>classProgram(staticvoidMain(string[]args)(inti,j;/Z循环变量intsum=0; /Z总分intaverage; /Z平均分intscore; /Z输入的分数intcount=0;〃分数在85分以上的学员数目〃外层循环控制逐个计算每个班级for(i=0;i<3;i++)(sum=0;/Z总分清〇,重新计算Console.WriteLine("\n请输入第{〇}个班的成绩”,i+1);/Z内层循环计算每个班级的总分for0=0;j<4;j++)(Console.WHte("第{0}个学员的成绩:",j+1);score=int.Parse(Console.ReadLine());sum=sum+score;//如果成绩不高于85分,继续执行,跳过计数if(score<85)(continue;)count++;)average=sum/4;Console.WriteLine("第{0}个班的平均分为:⑴分",i+1,average);}Console.WriteLine("成绩在85分以上的学员有{〇}人".count);Console.ReadLine();)})二十、输入一个字符串,输出其中的每个字符usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello{III<summary>II!此程序演示如何使用foreach循环III</summary>classProgramstaticvoidMain(string[]args)/Z输入提示Console.WriteLine("请输入一个字符串:/Z从控制台读入字符串stringline=Console.ReadLine();/Z循环输出字符串中的字符foreach(charcinline)(Console.WriteLine(c);}Console.ReadLine();)))二H"一ヽswitch的使用stringtime=Console.ReadLineQ; /Z输入时间switch(time)/Z判断case"6":Console.WriteLine("该起床了");break;case"12":Console.WriteLine("该吃饭了");break;default:Console.WriteLine("该睡觉了");break;}usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello{III<summary>II!练习switch的用法III</summary>classProgramstaticvoidMain(string[]args)Console.WriteLine("现在几点了?(输入一个整数)");stringtime=Console.ReadLine(); /Z输入时间switch(time)/Z判断(case"6":Console.WriteLine("该起床了");break;case"12":Console.WMteLine("该吃饭了");break;default:Console.WMteLine("该睡觉了");break;)Console.ReadLine();)))二十二、输入一个时间(整数)-在6-10点之间,输出“上午好”・在11-13点之间,输出“中午好”-在14-18点之间,输出“下午好”-其他情况输出“休息时间”usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello(III<summary>III此示例演示贯穿case的break///</summary>classProgram(staticvoidMain(string[]args)(Console.WriteLine("请输入当前的时间:");stringtime=Console.ReadLine();//接受输入switch(time)〃根据时间输出case"6":case"7":case"8":case"9":case"10":Console.WriteLine("上午好");break;case"11":case"12":case"13":Console.WHteLine("中午好'');break;case"14":case"15":case"16":case"17":case"18":Console.WriteLinef,T午好");break;default:Console.WriteLine("休息时间");break;Console.ReadLine();}))二十三、有两名学员的姓名、考试科目、成绩,根据输入的姓名,按以下方式输出该名学员的成绩usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello{III<summary>II!此代码演示如何使用switch语句III</summary>classProgram(staticvoidMain(string[]args)stringnamel="张三"; //第一个学员姓名stringname2="李四";/Z第二个学员姓名stringsubjectl="C#";/Z第一个学员考试科目stringsubject2="Java";/Z第二个学员考试科目intscorel=91; /Z第一个学员考试分数intscore2=89; //第二个学员考试分数/Z输入提示Console.WriteLine("请选择输出哪个学员的信息:张三/李四");stringchoice=Console.ReadLine();/Z接收输入/Z判断输入,选择输出Console.WriteLine("姓名ゝt科目't成绩");switch(choice)(case"张三":Console.WriteLine("{0}\t{1}\t{2}",namel,subjectl,scorel);break;case"李四":Console.WriteLine("{0}\t{1}\t{2}",name2,subject2,score2);break;default:Console.WMteLine("抱歉!没有你要找的学员!");break;)Console.ReadLine();)}}二十四、if嵌套语句usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello{III<summary>II!此程序演示如何使用嵌套if结构///</summary>classProgramstaticvoidMain(string[]args)intprice=4000;//机票的原价intmonth; //出行的月份inttype; /Z头等舱为1,经济舱为2Console.WriteLine("请输入您出行的月份:1-12");month=int.Parse(Console.ReadLine());Console.WriteLine("请问您选择头等舱还是经济舱?头等舱输入1,经济舱输入2");type=int.Parse(Console.ReadLine());if(month>=5&&month<=10)/Z旺季(if(type==1) 〃头等舱(Console.WriteLine("您的机票价格为:{0}",price*0.9);)elseif(type==2)/Z经济舱Console.WMteLine("您的机票价格为:{〇}",price*0.75);)else/Z淡季(if(type==1)〃头等舱(Console.WriteLine("您的机票价格为:{0}",price*0.6);)elseif(type==2)/Z经济舱(Console.WhteLine("您的机票价格为:{〇}",price*0.3);))Console.ReadLine();)))二十五、范例:机票预定:输出实际机票价格原价为4000元5-10月为旺季,头等舱打9折,经济舱打7.5折
其他时间为淡季,头等舱打6折,经济舱打3折需要两次判断首先判断是旺季还是淡季再判断头等舱还是经济舱嵌套if实现usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceHello{II
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- php开发技术面试题及答案
- 邮储银行2025白银市秋招笔试专业知识题专练及答案
- 邮储银行2025南充市秋招笔试热点题型专练及答案
- 中国银行2025齐齐哈尔市秋招笔试价值观测评题专练及答案
- 交通银行2025莆田市秋招英文面试题库及高分回答
- 邮储银行2025长春市秋招笔试性格测试题专练及答案
- 建设银行2025秋招群面模拟题及高分话术云南地区
- 农业银行2025新乡市秋招笔试专业知识题专练及答案
- 农业银行2025吴忠市秋招笔试创新题型专练及答案
- 建设银行2025山南市秋招笔试EPI能力测试题专练及答案
- PEP小学英语单词表(3-6年级)
- 2020小学一年级语文上册新教材教材分析解读课件
- 忠县介绍课件
- DB4401-T 43-2020 反恐怖防范管理+防冲撞设施-(高清现行)
- 保障和改善民生课件
- 教学课件:《新能源材料技术》朱继平
- 专业技术职称与职业(工种)技能人才评价对应表(试行)
- DB37∕T 4328-2021 建筑消防设施维护保养技术规程
- 银行信贷实务与管理课件
- 实习任务书(标准模版)
- 钢结构加工制造方案(60页)
评论
0/150
提交评论