One, if statement
Statement form:
if (expression)
{
Statements executed by <code><code>
}
The statements in {} are executed only if the value of the expression is true or not 0 o'clock; If-else is a pair, but sometimes there is only if and there is no else. Let's take a look at an example.
{ double x; Console.WriteLine ("Test If--else"); Console.WriteLine ("Enter a number:"); String data = console.readline (); X = convert.todouble (data); //if-else if (x > 1000) //input x=123; x>1000 not valid { Console.WriteLine ("X has one");//Not executed } else //again to judge, at this time know x<1000, since x<1000, look at the other situation, if (x > 100)//x > 100 { Console.WriteLine ("x>100"); } Else if (x > 0)//x > 0 { Console.WriteLine ("X is less than than" ); } Else { Console.WriteLine ("X<0"); } Console.WriteLine (x); console.readkey ();} |
The result of the input x=135 is: Nested of If: Nesting of if (x > 1000)//if statements { if (x==9000) { Console.WriteLine ("x=9000"); } if (x = = 8000) { Console.WriteLine ("x=8000"); } if (x > 5000) { Console.WriteLine ("x>5000"); } The compiler will judge by article, see which statement is set up to execute Console.WriteLine ("X has a"); } |
It can be seen from the results that, although there are so many if branches, only the conditions are fulfilled, if statements can include nesting, or if there is an if under if, as can be seen in the example above. The If statement handles two branches and uses the IF-ELSE-IF structure when handling multiple branches, but if there are more branches, the more nested IF statements layer, the larger and more difficult it is to understand the program. This article is published in the introductory web of programming: www.bianceng.cn
Two. Switch-case
The basic usage of switch-case is as follows:
switch (expression) { case Constant expression 1: statement 1; Break case constant expression 2: Statement 2; break; ..... case constant expression N: Statement N; break; } |
Public static void week () { Console.WriteLine ( "Enter an integer--4"); String xingqi=null; Xingqi = console.readline (); Int day = convert.toint32 (Xingqi); switch (Day)//day type cannot be float or other non-integer { case 1: console.writeline ("Monday"); break; case 2: console.writeline ("Turseday"); break; case 3: console.writeline ("Week 3"); break; case 4: console.writeline ("Week 4"); break; } Console.readkey (); } |
String str = Console.ReadLine (); Switch (STR) { Case "HI": Console.WriteLine ("Hi"); Break Case "Hello": Console.WriteLine ("Hello"); Break } Console.readkey (); |
The results of the demo are shown below: |
Also note that if the case "hi" after no break; change the program to: Switch (str) { Case "HI": Case "Hello": Console.WriteLine ("Hello"); Break } |
The results are: |
Of course, day can be changed to a string character, so match some string constants in the case.
Please do your own programming experience.