vc#2005 Quick Start using the IF statement

Source: Internet
Author: User
Tags date comparison datetime execution expression integer variable visual studio
QuickStart | Statement If you want to execute two different blocks of code based on the result of a Boolean expression, you can use the IF statement.

Understanding the syntax of an if statement

The syntax format of the IF statement is as follows (if and else is the keyword):

if (booleanexpression)
statement-1;
Else
Statement-2;
If booleanexpressionEvaluates to true, runs the Statement - 1; otherwise, run Statement - 2。 else keyword and subsequent Statement - 2Is dispensable. If there is no else clause, then the booleanexpressionIf False, nothing happens.

For example, the following if statement is used to increment the second hand of a stopwatch (temporarily ignoring minutes). If the value of the seconds is 59, reset to 0, otherwise use the operator + + to increment:

int seconds;
...
if (seconds = 59)
seconds = 0;
Else
seconds++;

Use Boolean expressions only!

An expression in an If statement must be placed in a pair of parentheses. In addition, an expression must be a Boolean expression. In other languages (especially C and C + +), you can also use an integer expression that automatically converts an integer value to True (not 0 values) or False (0 values). C # does not allow this. If you write an expression like this, the compiler will report an error.

If you accidentally write an assignment expression in an if statement instead of performing an equality test, the C # compiler can recognize your error. For example:

int seconds;
...
if (seconds = 59)//compile-time error
...
if (seconds = 59)//Correct

Accidentally writing an assignment expression is another reason why C and C + + programs are prone to bugs. In C and C + +, the assigned value (59) is silently converted to a Boolean value (any Non-zero value is treated as true), causing the code to execute the IF statement every time.

Finally, you can use a Boolean variable as an expression, as shown in the following example:

BOOL Inword;
...
if (Inword = = true)//can be, but not commonly used
...
if (Inword)//Better

   use blocks to group statements

Sometimes, you need to run two or more statements if a Boolean expression is true. You can group the statements that you want to run into a new method, and then call that method. However, a simpler approach is to group the statements into a block. A block is a series of statements that are closed with a pair of curly braces. In the following example, two statements reset the seconds variable to zero and increment the minutes variable. We use a block to group the two statements. If the value of seconds equals 59, the block is executed:

int seconds = 0;
int minutes = 0;
...

if (seconds = 59)
{
seconds = 0;
minutes++;
}
Else
seconds++;


Important Note If the braces are omitted, two serious consequences will be caused. First, the C # compiler associates only the first statement (seconds=0) with an if statement, and the Next statement (minutes++) will no longer be part of the IF statement. Second, when the compiler encounters the Else keyword, it is not associated with the previous if statement, so a syntax error is reported.

nested IF statement

You can nest other if statements in an if statement. This allows you to link a series of Boolean expressions, which will be tested sequentially until one evaluates to True. In the following example, if the day value is 0, the first test evaluates to true, and the value "Sunday" is assigned to the Dayname variable. If the day value is not 0, the first test fails and the control is passed to the ELSE clause. The clause will run the second if statement, comparing the value of day with 1. Note that the second if is executed only if the first if test is false. Similarly, the third if is executed only if the first and second if test is false.

if (day = = 0)
Dayname = "Sunday";
else if (day = 1)
Dayname = "Monday";
else if (day = 2)
Dayname = "Tuesday";
else if (day = 3)
Dayname = "Wednesday";
else if (day = 4)
Dayname = "Thursday";
else if (day = 5)
Dayname = "Friday";
else if (day = 6)
Dayname = "Saturday";
Else
Dayname = "Unknown";
In the following exercise, we'll write a method that uses nested IF statements to compare two dates.

Write an If statement

1. Start Microsoft Visual Studio 2005.

2. Open the selection project, which is located under the My Documents folder\microsoft Press\visual CSharp Step by Step\chapter 4\selectionSub folder.

3. Select "Debug" | " Start execution (without debugging).

Visual Studio 2005 will build and run the application. Two DateTimePicker controls are displayed on the form, named First and second (the control displays a calendar that allows users to select a date by clicking the Drop-down button). Two controls are currently set to today's date.

4. Click the Compare button.

The following is displayed in the text box:

Second:false
!= Second:true
< Second:false
<= Second:false
> Second:true
>= Second:true
The above results are obviously problematic! As shown in Figure 1, the Boolean expression, second, should be true because both the second and the both are set to today's date. In fact, in the above results, it seems that only the operator < and operator >= The result is correct!


Figure 1 Content in a text box

5. Click Quit.

The Visual Studio 2005 programming environment will then be returned.

6. Display the Form1.cs code in the Code and Text Editor window to find the Compare_click method, as follows:

private int Compare_click (object sender, System.EventArgs e)
{
int diff = Datecompare (. Value, second. Value);
Info. Text = "";
Show ("second", diff = 0);
Show ("The!= second", diff!= 0);
Show ("A < second", diff < 0);
Show ("The <= second", diff <= 0);
Show ("A > second", diff > 0);
Show ("The >= second", diff >= 0);
}
This method is executed when you click the Compare button on the form. This method gets the date values that are displayed in the two DateTimePicker controls on the form and another method called Datecompare to compare them. We'll discuss the datecompare approach in the next step, but here's a simple one. The effect of this method is to compare its two parameter values and return an integer value based on the result of the comparison. Returns 0 if two values are the same, or 1 if the value of first is less than second, or +1 if the value is greater than second (if a date is behind another date on the calendar, say the former is greater than the latter).

The Show method is used to display the comparison results in the Info text box control on a form.

7. Find the Datecompare method, as follows:

private int Datecompare (datetime lefthandside, datetime righthandside)
{
Todo
Return 42;
}
The method currently returns the same value after the call, rather than returning 0,-1 or + 1 by comparing the parameter values. This explains why applications don't work as we expect them to! Now, you need to implement this method so that it compares two dates correctly.

8. Remove//TODO comments and return statements from the Datecompare method.

9. Enter the following statement in the Datecompare method body:

int result;
if (Lefthandside.year < righthandside.year)
result =-1;
else if (Lefthandside.year > Righthandside.year)
result = +1;
else if (Lefthandside.month < Righthandside.month)
result =-1;
else if (Lefthandside.month > Righthandside.month)
result = +1;
else if (Lefthandside.day < Righthandside.day)
result =-1;
else if (Lefthandside.day > Righthandside.day)
result = +1;
Else
result = 0;
return result;
If Lefthandside.year < righthandside.year and Lefthandside.year > Righthandside.year are false, then lefthandside.year = = Righthandside.year must be true, the program flow will be transferred correctly, starting to compare the month properties of LHS and RHS. Similarly, if Lefthandside.month < Righthandside.month and Lefthandside.month > Righthandside.month is false, then Lefthandside.month = = Righthandside.month is definitely true, and the program will start comparing the day property of LHS and RHS. Finally, if Lefthandside.day < Righthandside.day and Lefthandside.day > Righthandside.day are false, then lefthandside.day = = Righthandside.day is definitely true, and since at this point the month and year properties are definitely true, two dates are definitely the same.

10. Select "Debug" | " Start execution (without debugging).

The application will be rebuilt and restarted. Similarly, two DateTimePicker controls (first and second) will be set to today's date.

11. Click the Compare button.

The following is displayed in the text box:

Second:true
!= Second:false
< Second:false
<= Second:true
> Second:false
>= Second:true
The result is the right one.

12. The date of second this DateTimePicker control will be transferred to tomorrow.

13. Click the Compare button again.

The following is displayed in the text box:

Second:false
!= Second:true
< Second:true
<= Second:true
> Second:false
>= Second:false
Likewise, these results are correct.

14. Click Quit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.