Bài giảng C# 2010 - Chapter 3: Control Statements Handle Exception

The for repetition structure

Syntax: for (Expression1, Expression2, Expression3)

Expression1 = names the control variable

Can contain several variables

Expression2 = loop-continuation condition

Expression3 = incrementing/decrementing

If Expression1 has several variables, Expression3

 must have several variables accordingly

++counter and counter++ are equivalent

Variable scope

Expression1 can only be used in the body of the for loop

When the loop ends the variable expires

 

pptx46 trang | Chuyên mục: Visual C# | Chia sẻ: dkS00TYs | Lượt xem: 1728 | Lượt tải: 1download
Tóm tắt nội dung Bài giảng C# 2010 - Chapter 3: Control Statements Handle Exception, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 13/05/2013 ‹#› 2 Format Code Format Code Description C or c Formats the string as currency. Precedes the number with an appropriate currency symbol ($ in the US). D or d Formats the string as a decimal. Displays number as an integer. N or n Formats the string with commas and two decimal places. 3 Format Code Format Code Description E or e Formats the number using scientific notation with a default of six decimal places F or f Formats the string with a fixed number of decimal places (two by default). G or g General. Either E or F. X or x Formats the string as hexadecimal. Logical and Conditional Operators Logical AND(&) Conditional AND (&&) Logical OR (|) Conditional OR (||) Logical NOT (!) Logical exclusive OR or XOR (^) 1 2 3 4 5 6 Used to add multiple conditions to a statement exp1 exp2 exp1 && exp2 false false false false true false true false false true true true 	Truth table for the && (logical AND) operator. Exp1 exp2 exp1 || exp2 false false false false true true true false true true true True 	Truth table for the || (logical OR) operator. exp1 exp2 exp1 ^ exp2 false false false false true true true false true true true false 	Truth table for the logical exclusive OR (^) operator. expression !expression false true True false 	Truth table for operator! (logical NOT). Control Structures Program of control Program performs one statement then goes to next line Sequential execution Different statement other than the next one executes Selection structure The if and if/else statements Repetition structure The while and do/while loops The for and foreach loops Flowcharting C#’s sequence structure. add grade to total add 1 to counter total = total + grade; counter = counter + 1; if Selection Structure Causes the program to make a selection Chooses based on conditional Any expression that evaluates to a bool type True: perform an action False: skip the action Single entry/exit point Require no semicolon in syntax if Selection Structure do something conditions true false If/else Selection Structure Alternate courses can be taken when the statement is false Rather than one action there are two choices Nested structures can test many cases Structures with many lines of code need braces ({) Can cause errors Fatal logic error Nonfatal logic error If/else Selection Structure Conditions do something do something else false true Conditional Operator (?:) C#’s only ternary operator Similar to an if/else structure The syntax is: boolean value ? if true : if false MessageBox.Show(dtb>=5? “Dau”: “Rot”); Loops Repeating a series of instructions Each repetition is called an iteration Types of Loops Do Use when the number of iterations is unknown For Use when the number of iterations known while Repetition Structure true false do something conditions for Repetition Structure The for repetition structure Syntax: for (Expression1, Expression2, Expression3) Expression1 = names the control variable Can contain several variables Expression2 = loop-continuation condition Expression3 = incrementing/decrementing If Expression1 has several variables, Expression3 must have several variables accordingly ++counter and counter++ are equivalent Variable scope Expression1 can only be used in the body of the for loop When the loop ends the variable expires for Repetition Structure for ( int i = 1; i <= 5; i++ ) Initial value of control variable Increment of control variable Control variable name Final value of control variable for keyword Loop-continuation condition for Repetition Structure counter++ Establish initial value of control variable. Determine if final value of control variable has been reached. counter <= 10 Console.WriteLine ( counter * 10 ); true false int counter = 1 Body of loop (this may be multiple statements) Increment the control variable. switch Multiple-Selection Structure The switch statement Constant expressions String Integral Cases Case ‘x’ : Use of constant variable cases Empty cases The default case The break statement Exit the switch statement switch Multiple-Selection Structure break; case : a case a action(s) true false . . . break; case b action(s) break; false false case : z case z action(s) break; default action(s) true true case : b do/while Repetition Structure The while loops vs. the do/while loops Using a while loop Condition is tested The the action is performed Loop could be skipped altogether Using a do/while loop Action is performed Then the loop condition is tested Loop must be run though once Always uses brackets ({) to prevent confusion do/while Repetition Structure int counter = 1; do { 	Console.WriteLine( counter ); 	counter++; } while ( counter <= 5 ); } // end method Main 1 2 3 4 5 do/while Repetition Structure true false action(s) condition Statements break and continue Use Used to alter the flow of control The break statement Used to exit a loop early The continue statement Used to skip the rest of the statements and begin the loop at the first statement in the loop Programs can be completed without their usage Handle Exception An exception occurs when a program encounters any unexpected problems. Your program should be able to handle these exceptional situations and, if possible, gracefully recover from them. This is called exception handling. ApplicationException Represents exceptions thrown by the applications SystemException Represents exceptions thrown by the CLR try Block try { //Code that may cause Exception } catch Block try {//code that may cause exception } catch (ArithmeticException ex1) {//Process Exception here } catch (EvaluateException ex2) {//Process Exception here } The throw statement if (n < 0) { ArithmeticException ex1 = new ArithmeticException("n must greater than Zero"); throw ex1; } finally Block The finally block contains code that always executes, whether or not any exception occurs try {//code here } finally {//do something } Define New Exception class CMyException : ApplicationException { private Exception innerException; private string m_strMsg; public string CustomMessage {get { return this.m_strMsg; } set { this.m_strMsg = value; } } public CMyException(){ } public CMyException(string strMsg,Exception ex) { this.m_strMsg = strMsg; this.innerException = ex; } } Define New Exception try { int t = 0,n=5; n = n / t; } catch (Exception ex) { CMyException myEx=new CMyException ("Lỗi rồi", ex.InnerException); MessageBox.Show(myEx.CustomMessage); } Error provider Control Name TextBox txtName TextBox txtAge DateTimePicker dateTimePicker1 Button btnDangKy ErrorProvider errorProvider1 private bool validateName(){ bool bValid = true; txtTen.Text.Trim(); if (txtTen.Text == ""){ bValid = false; errorProvider1.SetError(txtTen, "Tên không được để trống"); } else{ errorProvider1.SetError(txtTen, ""); } return bValid; } private bool validateAge() { bool bValid = true; int tuoi; bValid = Int32.TryParse(txtTuoi.Text, out tuoi); if (!bValid || tuoi < 18){ errorProvider1.SetError(txtTuoi, "Tuổi nhập không hợp lệ"); bValid = false; }else { errorProvider1.SetError(txtTuoi, ""); } return bValid; } private bool validateDate() { bool bValid = true; if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Sunday) { errorProvider1.SetError(dateTimePicker1 , "Không được đăng ký vào ngày CN"); bValid = false; } else { errorProvider1.SetError(dateTimePicker1,""); } return bValid; } private void btnDangKy_Click(object sender, EventArgs e) { bool bValidName=validateName(); bool bValidAge=validateAge(); bool bValidDate=validateDate(); if (!bValidName || !bValidAge || !bValidDate) { //Error here } else { //Success here } } END 

File đính kèm:

  • pptxBài giảng C# 2010 - Chapter 3 Control Statements Handle Exception.pptx
Tài liệu liên quan