In this lesson we are going to learn about a conditional statement called the switch statement. Usually if and if else [color=#3333FF]statements are taught before switch statements. Although these are very useful, I find the switch to be easier and more fun to use.
The program written below is very similar to the previous program where the user is asked to enter their name, however now the program will look for four distinct string values and ti will generate output according to the string entered. Here are the things to observe when reading and replicating this program.
1.) 2 string variables are declared (greeting and fullName)
2.) A value is assigned using our Console.ReadLine() method. (Point where we insert the value.)
3.) the value of the variable greeting depends on the value entered for the variable fullName
4.) The program is case sensitive. Basically this is because different case letters have different values. So a lower case t will not evaluate the same as an upper case T. So ulitmately what does this mean. Well let's if you entered george bush as opposed to George Bush, you would get the default greeting because the program would not recognize your lower case entry of george bush as George Bush. If it does not make sense, run the program and change the case. You will see what I mean.
5.) Lastly, the default option is included in the case statement for the instances where neither of the output meets any of the criteria of the case statement.
CODE:
using System;
namespace ConsoleApplication
{
///
/// Testing out the case Statement
///
class switchStatement
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
string fullName, greeting;
Console.Write("Please enter your name: ");
fullName = Console.ReadLine();
switch (fullName)
{
case "YOUR NAME HERE":
greeting = "You are the best!!";
break;
case "Bill Gates":
greeting = "You are super wealthy!";
break;
case "George Bush":
greeting = "hmmm????";
break;
case "Kenneth Lay":
greeting = "How is Court Going?";
break;
default:
greeting = "I'm sorry I did not recognize you!";
break;
}//end switch statement
Console.WriteLine();
Console.WriteLine(greeting);
Console.WriteLine();
Console.WriteLine("Press [ENTER] to Exit");
Console.ReadLine();
}//end Main
}//end class "switchStatement
}//end namespace
As I might have mentioned on my previous post I am using Visual Studio. I believe the Express version is out on the web for free. However you might need to install NetFramework before you proceed to install VS.
Also, just like the previous program, an adobe file will be attached with the source code. variables and comments are all color coded.
No comments:
Post a Comment