Chapter 6 control statement
There is a statement that you can find in each programming language control process statement. In this chapter, I introduced the C # control statement, and they are divided into two main parts:
. Select statement
. loop statement
If you are C or C programmers, many information will make you feel similar; however, you must know that there are still differences. P>
6.1 Select statement
When you use the selected statement, you define a control statement, and its value controls which statement is executed. Use two selection statements in C #:
. IF statement
. Switch statement p>
6.1.1 if statement
The first and most commonly used statement is an IF statement. Whether or not the statement is executed depends on the Boolean expression:
IF (Boolean expression)
Of course, there is also an ELSE branch. When the value of the Boolean expression is false, the branch is performed:
IF (Boolean expression) contains statements ELSE
Check an example of a non-zero string before performing some statements: p>
if (0! = StrTest.Length)
{
} P>
This is a Boolean expression. (! = Said it is not equal.) However, if you from C or C , you may be used to writing code like this:
IF (strTest.length)
{
} P>
This is no longer working in C #, because the IF statement only allows the result of the Boole data type, and the LENGTH property object of the string returns an integer. The compiler will appear the following error message:
Error CS0029: Cannot Implicitly Convert Type 'Int' To 'Bool' (cannot implicantly convert type 'int "is' BOOL'.) The habit you must change, while the lower side will not The assignment error occurs in the IF statement:
IF (nmyvalue = 5) ... p>
The correct code should be p>
if (nmyvalue == 5) ... p>
because of equal comparison = = Implement, just like C and C . Look at the following useful comparison operators (but not all data types are valid):
== - If the two values are the same, return true.
! = - If the two values are different, return false.
<, <=,>,> = - If the relationship is satisfied (less than, less than or equal to, greater than, greater than or equal to), return true.
Each operator is performed by the overload operator, and this execution is specified for the data type. If you compare two different types, for the compiler, there must be an implicit conversion to automatically create the necessary code. However, you can perform an explicit type conversion.
The code in Listing 6.1 demonstrates some different cases of the IF statement, and also demonstrates how to use string data types. The main idea of this program is to determine whether the first parameter passed to the application starts with uppercase letters, lowercase letters or numbers. P>
Listing 6.1 Determines the character of the character p>
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:}
twenty one:
22: chletter = char.fromstring (args [0]);
23: IF (chletter> = 'a' && chletter <= 'z')
24: Console.WriteLine ("{0} is lowercase", chletter);
25:
26: IF (char.isdigit (chlletter = args [0])))))))))
27: console.writeLine ("{0} is a digit", chletter;
28:
29: RETURN 0;
30:}
31:} p>
Begin the first IF segment of the 7th line 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.
You can take a variety of methods to extract a single character from a string - can be used as a character index like a line 13, or a static fromString method of the CHAR class, which returns the first character of the string.
The IF statements of the 16th to 20th line use a nested IF state block to check the uppercase letters. With logic "and" operators (&&) can be qualified for lowercase letters, and finally, by using a static function isDigit using a CHAR class, you can complete the detection of numbers.
In addition to "&&" operators, there is another conditional logic operator, which is representative "or" "||". Both logical operators are "short circuit". For the "&&" operator, it means that if the condition "and" the first result of the expression returns a false value, the remaining conditions "and" expressions will not be evaluated. Comparison, "||" operator When the first true condition is satisfied, it "short circuit".
I want everyone to understand that to reduce the calculation time, you should put the expression that is most likely to "short circuit" in front. Also you should be clear, calculate some of the values in the IF statement in the danger. P>
if (1 == 1 || (5 == (strLength = str.length))))
{
Console.writeLine (Strlength);
} P>
Of course, this is an extremely exaggerated example, but it illustrates this point of view: The first statement is true, then the second statement will not be executed, it makes the variable Strlength Maintain the original value. Give everyone an advice: Do not assign a value in the IF statement with conditional logic operators. P>
6.1.2 Switch statement is compared to the IF statement, the Switch statement has a control expression, and the contents of the statement are running in accordance with the constant of the control expressions associated. P>
switch (Control Expression)
{
Case constant expression:
Internal statement
DEFAULT:
Internal statement
} P>
Control expressions allowed by: Sbyte, Byte, Short, Ushort, Uint, long, ulong, char, string, or enumeration type. As long as other different data types can be implicitly converted to any type described, it is also very good to use it as a control expression.
Switch statement is performed in the following order:
1, control expression evaluation
2. If the constant expression after the CASE tag meets the value obtained by the control statement, the contents are executed.
3. If there is no constant expression conforms to the control statement, the inherent statement in the Default tag is executed.
4. If there is no Case tag, and there is no DEFAULT tag, control the end of the end of the Switch segment.
Please check out the Switch statement in more detail, see Listing 6.2, which demonstrates the number of days in a month (ignore the year) with the Switch statement (ignore the year)
Listing 6.2 Use the switch statement to display the number of days in one month p>
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> 12) 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;
twenty one: }
22: console.writeline ("{0} days in this month", nDays);
twenty three: }
24:} p>
Switch is included in lines 13-12. For C programmers, this looks very similar because it does not use the BREAK statement. Therefore, there is a more vital importance. You have to add a BREAK statement (or a different jump statement) because the compiler will remind, not allowing direct access to the next part.
What is direct? In c (and C ), ignore Break and write code as follows:
NVAR = 1
Switch (nvar)
{
Case 1:
DOSMETHING ();
Case 2:
Domore ();
} P>
In this example, after executing the code of the first CASE statement, the code directly to other CASE tags is executed until a BREAK statement exits the Switch segment. Although it is sometimes a powerful function, it is often difficult to discover defects. But if you want to perform the code of other CASE tags, what should I do? There is an approach that it is displayed in Listing 6.3. P>
Listing 6.3 Using Goto Labels and Goto Default P>
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: // 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;
23: // Everything beyond a goto will be Warned AS
24: // Unreachable Code
25: DEFAULT:
26: console.writeLine ("Random Number {0}", NRNDNUMBER);
27:}
28:}
29:} p>
In this example, the value for controlling the expression is generated by the Random class (lines 7 ~ 9). The Switch section contains two trip statements that are valid for the Switch statement.
Goto Case Tags: Jump to the illustrated label
Goto Default: Jump to Default Tag
With these two jump statements, you can create functions as C, but direct access is no longer automatic. You must ask it clearly.
The deeper meaning of the direct function is no longer: You can arrange the label, such as putting the DEFAULT tag in front of all other tags. To illustrate it, I created an example, deliberately did not end the loop: p>
Switch (nsomething)
{
DEFAULT:
Case 5:
Goto Default;
} P>
I have retained a discussion of one of the SWICH statement features until the end - in fact you can use a string as a constant expression. This for VB programmers may sound as big news, but programmers from C or C will like this new feature.
Now, a SWITCH statement can be used as the string constant as shown below. P>
string strate = "chris";
Switch (strTest)
{
Case "Chris":
Console.writeline ("Hello Chris!");
Break;
} P>
6.2 circulating statement
When you want to repeat certain statements or segments, based on the current different tasks, C # provides 4 different loop statements to choose to use:. For statement
. FOREACH statement
. WHILE statement
. DO statement p>
6.2.1 for statement
When you know how many statements should be performed in advance, the for statement is especially useful. When the condition is true, the conventional syntax allows repeatedly executed statements (and cyclic expressions):
FOR (initialization; condition; loop)
Note that initialization, conditions, and cycles are optional. If you have ignored the condition, you can generate a dead loop, to use the jump statement (BREAK or GOTO) to exit. P>
for (;;)
{
Break; // Due to certain reasons
} P>
Another focus is that you can add multiple three parameters that are added by a comma-separated statement to the FOR cycle. For example, you can initialize two variables, have three conditional statements, and repeat 4 variables.
As a C or C programmer, you must understand only one change: the conditional statement must be a Boolean expression, just like the IF statement.
Listing 6.4 includes an example of using the for statement. It shows how to calculate a step, which is called fast than using a recursive function. P>
Listing 6.4 Calculates a step in the For cycle p>
1: use 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:} p>
Although this example is too drag, it is an opening of how to use the for statement. First, I should initialize internal declaration variable ncurdig:
For (Long nCurdig = 1; ncurdig <= ncomputeto; ncurdig ) nFactorial * = ncurdig;
Another choice to ignore the initialization is as follows, because the 10th line initializes the variable outside the FOR statement. (Remember that C # needs to initialize the variable):
For (; ncurdig <= ncomputeto; ncurdig ) nFactorial * = ncurdig;
Another change is to remove operations into the contents:
nfactorial * = nCurdig ; NFACTORIAL * = NCURDIG ;
If I want to get rid of the conditional statement, all to do it is to add an IF statement, abort the loop with the BREAK statement: p>
for (;;)
{
IF (ncurdig> ncomputeto) Break; nfactorial * = ncurdig ;
} P>
In addition to exiting the BREAK statement of the for statement, you can also skip the current loop with Continue and continue the next loop.
For (; ncurdig <= ncomputeto;)
{
IF (5 == ncurdig) Continue; // This line skips the rest of the code
NFactorial * = ncurdig ; p>
} p>
6.2.2 foreach statement
A long function has been existed in the Visual Basic language is to collect enumerations by using the for Each statement. C # passes through the foreach statement, there is also a command to collect enumeration:
FOREACH (Type Identifier in Expression) Contained statements
The cyclic variable is declared by type and identifier, and the expression corresponds to the collection. The loop variable represents the collection element that the loop is running. P>
You should know that you can't assign a new value to the loop variable, or you can't treat it as a REF or OUT parameter. This references the code to be executed in the statement. P>
How do you say some kinds of support for Foreach statement? In short, classes must support methods with GetEnumerator () names, and the structure, class or interface returned by it must have a public method MoveNext () and public attribute Current. If you want to know more, please read the language reference manual, it has a lot of details about this topic. P>
For the example in Listing 6.5, I happen to choose a class and implement all of these needs. I use it to list all environment variables defined. P>
Listing 6.5 Read all environment variables p>
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 is {0} environment", envvars.keys.count);
10: Foreach (String strkey in envvars.keys)
11: {
12: console.writeLine ("{0} = {1}", strkey, envvars [strkey] .tostring ());
13:}
14:}
15:}
Returns a idictionary type interface for the call to GetEnvironmentvariables, which is a dictionary interface implemented by many classes in the .NET framework. With the iDictionary interface, you can access two collection: keys and values. In this example, I use KEYS in the foreach statement, then look for values based on the current KEY value (line 12).
When using foreach, as long as one problem: When determining the type of the loop variable, be careful. Selecting the type of error is not detected by the compiler, but it will be detected at runtime and will trigger an exception. P>
6.2.3 While Statement When you want to execute a statement 0 times or more, the While statement is what you look forward to: p>
While (Condition) Statement p>
conditional statement - it is also a Boolean expression - the number of times the control is executed. You can use the Break and Continue statements to control the execution statements in the While statement, which is the same as in the For statement.
To illustrate the WHILE use, Listing 6.6 shows how to use a StreamReader class to output a C # source file to the screen. P>
Listing 6.6 Displays the content of a file p>
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");
String strline = null;
10:
11: While (null! = (Strline = sr.readline ())))
12: {
13: console.writeline (strline);
14:}
15:
16: Sr.Close ();
17:}
18:} p>
The code opens the file whileSample.cs, then the read value is displayed on the screen when the Readline method returns a value that is not equal to NULL. Note that I use a assignment in the While condition statement. If there is more conditional statements that connect to && and ||, I can't guarantee whether they will be executed because there is a "short circuit". P>
6.2.4 DO statement
C # finally available loop statement is a DO statement. It is very similar to the While statement, and the conditions are only verified after the initial cycle. P>
DO
{
Internal statement
}
While (condition); p>
DO statement guarantees that the contents have been executed at least once, and as long as the condition evaluates is equal to true, they continue to be executed. By using the BREAK statement, you can force the run to exit the DO. If you want to skip this cycle, use the Continue statement.
An example of how to use the DO statement is displayed in Listing 6.7. It requests one or more numbers to the user, and calculates the average when the execution program exits the DO cycle. P>
Listing 6.7 Calculate the average value p>
1 in the DO loop; use:
2:
3: Class ComputeAvertApp
4: {
5: public static void main ()
6: {
7: computeaveRageapp theApp = new computeAVeApp ();
8: THEAPP.RUN ();
9: }
10:
11: Public void Run ()
12: {
13: double DVALUE = 0;
14: Double DSUM = 0;
15: int noofvalues = 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:} p>
In this example, I instantiate an object of the ComputeAvertApp type in a static main function. It also follows the RUN method of the instance, which contains all the necessary functions of the average.
The DO loop across the lines 19 ~ 31. The condition is set to set: Separate each question "Y" to determine if another value is to be added. Enter any other characters can cause the program to exit the DO block and the average value is calculated.
As you can see from mentioned examples, the DO statement and the WHILE statement is not very different - only the difference is when the conditions are evaluated. P>
6.3 small knot
This chapter explains how to use the various selection and loop statements used in C #. The IF statement may be the most commonly used statement in the application. When using calculations in Boolean expressions, the compiler will pay attention to you. However, you must ensure that the short circuit of the conditional statement does not stop the operation of the necessary code.
Switch statement - although it is similar to the corresponding part of the C language - but also improved. Direct access is no longer supported, and you can use a string label for C programmers, this is a new usage.
The last part of this chapter, I explain how to use for, foreach, while and DO statements. The statement completes various needs, including the loop of the fixed number of times, lists the statements that collect the elements and perform any number of any number of conditions based on certain conditions.