". NET programming Pioneer C #" sixth chapter control statement (Turn)

Source: Internet
Author: User
Tags foreach execution expression goto variables string tags uppercase letter valid
Programming | control | Statement SIXTH Chapter CONTROL statement
There is a statement that you can find in each programming language control flow statement. In this chapter, I introduce C # 's control statements, which are divided into two main sections:
。 SELECT statement
。 Loop statement
If you are a C or C + + programmer, a lot of information will make you feel like you did, but you have to know that there are some differences.

6.1 SELECT statements
When applying a selection statement, you define a control statement whose value controls which statement is executed. Two selection statements are used in C #:
。 If statement
。 Switch statement

6.1.1 If statement
The first and most commonly used statement is the IF statement. Whether the containing statement is executed depends on the Boolean expression:
if (Boolean expression) implicit statement
Of course, you can also have an else branch, which is executed when the value of the Boolean expression is false:
if (Boolean expression) contains statement else implicit statement
Check for an example of a non 0 long string before executing some statements:

if (0!= strtest.length)
{
}

This is a Boolean expression. (!= means not equal.) However, if you are from C or C + +, you may be accustomed to writing code like this:
if (strtest.length)
{
}

This no longer works in C # because the IF statement allows only the result of a Boolean (bool) data type, while the length Property object of the string returns an integer. The compiler will receive the following error message:
Error cs0029:cannot implicitly convert type ' int ' to ' bool ' (you cannot implicitly convert an ' int ' to ' bool '.) )

The top is the habit you have to change, and the bottom will no longer have an assignment error in the IF statement:
if (Nmyvalue = 5) ...

The correct code should be

if (Nmyvalue = 5) ...

Because equality comparisons are implemented by = =, as in C and C + +. See the following useful comparison operators (but not all data types are valid):
==--If two values are the same, return true.
!=--returns False if two values are different.
<=, >=--, if the relationship is satisfied (less than, less than or equal to, greater than, greater than, or equal to), returns True.
Each operator is executed by an overloaded operator, and this execution has a set of data types. If you compare two different types, there must be an implicit conversion for the compiler to automatically create the necessary code. However, you can perform an explicit type conversion.
The code in Listing 6.1 illustrates some of the different uses of the IF statement and also demonstrates how to use a string data type. The main idea of this program is to determine whether the first argument passed to the application starts with an uppercase letter, a lowercase letter, or a number.

Listing 6.1 determines the shape of the character

1:using System;
2:
3:class Nestedifapp
4: {
5:public static int Main (string[] args)
6: {
7:if (args. Length!= 1)
8: {
9:console.writeline ("Usage:one argument");
10:return 1; Error level
11:}
12:
13:char chletter = args[0][0];
14:
15:if (chletter >= ' A ')
16:if (chletter <= ' Z ')
17: {
18:console.writeline ("{0} is uppercase", chletter);
19:return 0;
20:}
21st:
22:chletter = char.fromstring (Args[0]);
23:if (Chletter >= ' a ' && chletter <= ' z ')
24:console.writeline ("{0} is lowercase", chletter);
25:
26:if (char.isdigit (chletter = args[0][0)))
27:console.writeline ("{0} is a digit", chletter);
28:
29:return 0;
30:}
31:}

The first if segment starting at line 7th detects whether the parameter array has only one string. If the condition is not met, the program displays usage information on the screen and terminates the operation.
There are several ways to extract a single character from a string-either by using a character index like line 13th, or by using the static FromString method of the Char class, which returns the first character of the string.
The IF statement block on line 16th to 20th checks uppercase letters with a nested IF statement block. The logic "and" operator (&&) is competent for the detection of lowercase letters, and finally, by using the static function IsDigit of the Char class, the detection of the number can be accomplished.
In addition to the "&&" operator, there is another conditional logic operator, which represents "or" "¦¦". Two logical operators are "short-circuit" type. For the "&&" operator, it means that if the condition "and" the first result of the expression returns a false value, the remaining condition "and" expression will no longer be evaluated. Correspondingly, the "¦¦" operator is "shorted out" when the first true condition is satisfied.
What I want you to understand is that to reduce the computational time, you should put the expression that is most likely to make the evaluation "short-circuit" in front of you. Again, you should be aware that there is a risk that some of the values in the IF statement will be replaced.

if (1 = = 1¦¦ (5 = = Strlength=str. Length)))
{
Console.WriteLine (Strlength);
}

Of course, this is an extremely exaggerated example, but it illustrates the view that the first statement is evaluated as true, then the second statement is not executed, which keeps the variable strlength the original value. Here's a tip: Never assign a value in an if statement that has a conditional logical operator.

6.1.2 Switch statement
The switch statement has a control expression compared to the IF statement, and the containing statements run according to the constants of the control expression they are associated with.

Switch (Control expression)
{
Case constant expression:
Implicit statement
Default
Implicit statement
}

The data types allowed by the control expression are: sbyte, Byte, short, ushort, uint, long, ulong, char, string, or enum type. It is also good to use it as a control expression as long as the other data types can be implicitly converted to any of the above types.
Switch statements are executed in the following order:
1, the control of expression evaluation
2. If the constant expression after the case label conforms to the value obtained by the control statement, the containing statement is executed.
3. If no constant expression conforms to the control statement, the implicit statement within the default tag is executed.
4. If there is no case label and no default label, the control turns to the end of the switch segment.
Before continuing to explore the switch statement in more detail, see Listing 6.2, which shows the number of days to display with a switch statement for one months (ignoring straddling)
Listing 6.2 shows the number of days in one months using a switch statement

1:using System;
2:
3:class Fallthrough
4: {
5:public static void Main (string[] args)
6: {
7:if (args. Length!= 1) return;
8:
9:int nmonth = Int32.Parse (Args[0]);
10:if (Nmonth < 1¦¦nmonth >) return;
11:int ndays = 0;
12:
13:switch (Nmonth)
14: {
15:case 2:ndays = 28; Break
16:case 4:
17:case 6:
18:case 9:
19:case 11:ndays = 30; Break
20:default:ndays = 31;
21:}
22:console.writeline ("{0} days in this month", ndays);
23:}
24:}


The switch segment is included in line 13th to 21st. For C programmers, this looks very similar because it does not use a break statement. Therefore, there is an important difference that is more vital. You must add a break statement (or a different jump statement), because the compiler will remind you not to allow direct access to the next part.
What is direct? In C (and C + +), it is completely legal to ignore the break and write code as follows:
NVar = 1
Switch (NVar)
{
Case 1:
DoSomething ();
Case 2:
Domore ();
}

In this example, after executing the code for the first case statement, the code will be executed directly to other case labels until a break statement exits the switch segment. Although sometimes this is a powerful feature, it more often produces bugs that are difficult to discover.
But what if you want to execute code for other case labels? There is a way, it appears in listing 6.3.

Listing 6.3 uses the goto label and goto Default in the Swtich statement

1:using System;
2:
3:class Switchapp
4: {
5:public static void Main ()
6: {
7:random objrandom = new Random ();
8:double Drndnumber = objrandom.nextdouble ();
9:int nrndnumber = (int) (Drndnumber * 10.0);
10:
11:switch (Nrndnumber)
12: {
13:case 1:
14://Do nothing
15:break;
16:case 2:
17:goto Case 3;
18:case 3:
19:console.writeline ("Handler for 2 and 3");
20:break;
21:case 4:
22:goto default;
://Everything beyond a goto would be warned as
://Unreachable code
25:default:
26:console.writeline ("Random number {0}", Nrndnumber);
27:}
28:}
29:}

In this example, the value that is used to control an expression is generated by the Random class (line 7th to 9th). The switch segment contains two jump statements that are valid for a switch statement.
Goto case Label: Jump to the indicated label
Goto default: Jump to Default label
With these two jump statements, you can create the same functionality as C, but the direct access is no longer automatic. You have to ask for it explicitly.
The deeper implication of not using a direct function is that you can arrange the labels arbitrarily, such as placing the default label in front of all other tags. To illustrate it, I created an example of deliberately not ending loops:

Switch (nsomething)
{
Default
Case 5:
goto default;
}

I've kept a discussion of one of the Swich statement functions until the end--you can actually use a string as a constant expression. This may not sound like a big news to a VB programmer, but programmers from C or C + + will love this new feature.
Now, a switch statement can check the string constants as shown below.

String strtest = "Chris";
Switch (strtest)
{
Case "Chris":
Console.WriteLine ("Hello chris!");
Break
}


6.2 Circular Statements
When you want to repeat certain statements or paragraphs, C # provides 4 different loop statements for you to use depending on the current task:
。 For statement
。 foreach statement
。 While statement
。 Do statement

6.2.1 For statement
A For statement is especially useful when you know in advance how many times an implicit statement should be executed. When the condition is true, the general syntax allows for repeated execution of the implicit statement (and the Loop expression):
for (initialization; condition; loop) Implicit statement
Please note that initialization, conditions, and loops are optional. If you ignore the condition, you can generate a dead loop that uses a jump statement (break or Goto) to exit.

for (;;)
{
Break For some reason
}


Another important point is that you can add more than one comma-separated statement to all three arguments for the for loop. For example, you can initialize two variables, have three conditional statements, and repeat 4 variables.
As a C or C + + programmer, you must understand the only change: A conditional statement must be a Boolean expression, like an if statement.
Listing 6.4 contains an example of using a for statement. It shows how to calculate a factorial faster than using recursive function calls.

Listing 6.4 calculates a factorial in the For loop

1:using System;
2:
3:class factorial
4: {
5:public static void Main (string[] args)
6: {
7:long nfactorial = 1;
8:long Ncomputeto = Int64.parse (Args[0]);
9:
10:long ncurdig = 1;
11:for (Ncurdig=1;ncurdig <= ncomputeto; ncurdig++)
12:nfactorial *= Ncurdig;
13:
14:console.writeline ("{0}! is {1} ", Ncomputeto, nfactorial);
15:}
16:}

Although this example is too dilatory, it serves as a starting point for how to use a for statement. First, I should have declared the variable ncurdig inside the initialization:
For (long ncurdig=1;ncurdig <= ncomputeto ncurdig++) nfactorial *=;
Another option that ignores initialization is the following line, because line 10th initializes the variable outside of the For statement. (Remember C # requires initialization of variables):
for (; Ncurdig <= Ncomputeto; ncurdig++) nfactorial *=;
Another change is to move the + + operator to a built-in statement:
for (; Ncurdig <= ncomputeto;) nfactorial *= ncurdig++;
If I also want to get rid of conditional statements, all I have to do is add an if statement and abort the loop with the break statement:

for (;;)
{
if (Ncurdig > Ncomputeto) break;
Nfactorial *= ncurdig++;
}


In addition to the break statement used to exit the For statement, you can also use continue to skip the current loop and continue with the next loop.
for (; Ncurdig <= Ncomputeto;)
{
if (5 = = Ncurdig) continue; This line skips the rest of the code.
Nfactorial *= ncurdig++;

}

6.2.2 foreach statement
One feature that has been in the visual Basic language for a long time is to collect enumerations by using the for each statement. C # through a foreach statement, there is also a command to collect enumerations:
foreach (type identifier in an expression) contains statements
A loop variable is declared by a type and an identifier, and the expression corresponds to a collection. A loop variable represents the collection element that the loop is running for.

You should know that you cannot assign a new value to a loop variable, nor can you treat it as a ref or out parameter. This refers to code that is executed in the containing statement.

How do you say that some classes support a foreach statement? In short, a class must support a method with a GetEnumerator () name, and the struct, class, or interface that it returns must have public method MoveNext () and public property current. If you want to know more, please read the Language Reference manual, it has a lot of details on this topic.

For the example in Listing 6.5, I accidentally selected a class to achieve all of these needs. I use it to enumerate all the environment variables that have been defined.

Listing 6.5 reads all the environment variables

1:using System;
2:using System.Collections;
3:
4:class Environmentdumpapp
5: {
6:public static void Main ()
7: {
8:idictionary envvars = Environment.getenvironmentvariables ();
9:console.writeline ("There are {0} environment variables declared", Envvars. Keys.count);
10:foreach (String strkey in Envvars. Keys)
11: {
12:console.writeline ("{0} = {1}", Strkey, Envvars[strkey]. ToString ());
13:}
14:}
15:}
The call to Getenvironmentvariables returns a IDictionary type interface, which is caused by the. NET Framework, the dictionary interface is implemented by many classes in the Through the IDictionary interface, you can access two collections: Keys and Values. In this example, I use the keys in a foreach statement and then look for values based on the current key value (line 12th).
When using foreach, just be aware of the problem: when determining the type of a loop variable, you should be cautious. Selecting the wrong type is not detected by the compiler, but it is detected at run time and an exception is thrown.

6.2.3 While statement
When you want to execute an implicit statement 0 or more times, the while statement is exactly what you expect:

while (condition) implicit statement

A conditional statement-it is also a Boolean expression-controls the number of times the containing statement is executed. You can use the break and continue statements to control the execution statement in the while statement, which runs exactly the same as in the For statement.
For example while, listing 6.6 shows how to use a StreamReader class to output C # source files to the screen.

Listing 6.6 shows the contents of a file

1:using System;
2:using System.IO;
3:
4:class Whiledemoapp
5: {
6:public static void Main ()
7: {
8:streamreader sr = file.opentext ("Whilesample.cs");
9:string strLine = null;
10:
11:while (null!= (StrLine = Sr. ReadLine ()))
12: {
13:console.writeline (StrLine);
14:}
15:
16:SR. Close ();
17:}
18:}


The code opens the file Whilesample.cs, and then when the ReadLine method returns a value that is not equal to NULL, the read value is displayed on the screen. Notice that I used an assignment in the while condition statement. If there are more conditional statements connected with && and ¦¦, I cannot guarantee that they will be executed because there is a possibility of a "short-circuit".

6.2.4 do statement
The last available loop statement in C # is a do statement. It is very similar to a while statement, and the condition is validated only after the initial loop.


Todo
{
Implicit statement
}
while (condition);

The Do statement guarantees that the containing statements are executed at least once, and that they continue to be executed as long as the condition is evaluated to be true. By using the break statement, you can force the run to exit the Do block. If you want to skip this one cycle, use the Continue statement.
An example of how to use the Do statement is shown in Listing 6.7. It requests one or more digits from the user and calculates the average after the execution program exits the Do loop.

Listing 6.7 calculates the average in the Do loop

1:using System;
2:
3:class Computeaverageapp
4: {
5:public static void Main ()
6: {
7:computeaverageapp Theapp = new Computeaverageapp ();
8:theapp.run ();
9:}
10:
11:public void Run ()
12: {
13:double dvalue = 0;
14:double dSum = 0;
15:int nnoofvalues = 0;
16:char chcontinue = ' y ';
17:string strinput;
18:
19:do
20: {
21:console.write ("Enter A Value:");
22:strinput = Console.ReadLine ();
23:dvalue = Double.Parse (strinput);
24:dsum + = Dvalue;
25:nnoofvalues++;
26:console.write ("Read another value?");
27:
28:strinput = Console.ReadLine ();
29:chcontinue = char.fromstring (strinput);
30:}
31:while (' y ' = = chcontinue);
32:
33:console.writeline ("The average is {0}", dsum/nnoofvalues);
34:}
35:}

In this example, I instantiate an object of the Computeaverageapp type in the static main function. It also then invokes the instance's Run method, which contains all the necessary functions to compute the average value.
The Do loop crosses line 19th to 31st. The condition is set: answer each question "Y" separately to determine whether you want to add another value. Entering any other character causes the program to exit the Do block and the average value is computed.
As you can see from the example mentioned, a do statement and a while statement are not very different-the only difference is when the condition is evaluated.

6.3 Summary
This chapter explains how to use the various selections and looping statements used in C #. An If statement may be the most commonly used statement in an application. When you use calculations in Boolean expressions, the compiler will notice for you. However, you must ensure that the short circuit of the conditional statement does not prevent the necessary code from running.
The switch statement-although similar to the corresponding part of C-is also improved. Direct access is no longer supported, and you can use string tags, which is a new usage for C programmers.
In the last part of this chapter, I explain how to use for, foreach, while, and do statements. Statement to complete various needs, including performing a fixed number of loops, enumerating the collection elements, and executing any number of statements based on certain criteria.

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.