using System;
public class MainClass {
static void Main() {
Console.WriteLine("Enter command:");
string resp = (Console.ReadLine()).ToLower();
switch (resp) {
case "a":
Console.WriteLine("Doing Task A");
break;
case "b":
Console.WriteLine("Doing Task B");
break;
case "c":
Console.WriteLine("Doing Task C");
break;
default:
Console.WriteLine("Bad choice");
break;
}
}
}
Development Class
Use while(true) to read console input
using System;
public class MainClass {
static void Main() {
string resp;
while (true) {
Console.WriteLine("Menu
1 - Task A");
Console.WriteLine("2 - Task B");
Console.WriteLine("E - E(xit)");
resp = (Console.ReadLine()).ToLower();
if (resp == "e") {
break;
}
}
}
}
Use do while to read console input
using System;
public class MainClass {
static void Main() {
string resp;
do {
Console.WriteLine("Menu
1 - Task A");
Console.WriteLine("2 - Task B");
Console.WriteLine("E - E(xit)");
resp = (Console.ReadLine()).ToLower();
}
while (resp != "e");
}
}
Terminate a control input
using System;
public class MainClass {
static void Main() {
string resp;
Console.WriteLine("Enter command ('x' to end):");
while ((resp = (Console.ReadLine()).ToLower()) != "x") {
switch (resp) {
case "a":
Console.WriteLine("Doing Task A");
break;
case "b":
Console.WriteLine("Doing Task B");
break;
default:
Console.WriteLine("Bad choice");
break;
}
}
}
}
Output with parameters
/*
Learning C#
by Jesse Liberty
Publisher: O'Reilly
ISBN: 0596003765
*/
public class AssignedValues {
static void Main( )
{
int myInt;
//other code here...
myInt = 7; // assign to it
System.Console.WriteLine("Assigned, myInt: {0}", myInt);
myInt = 5;
System.Console.WriteLine("Reassigned, myInt: {0}", myInt);
}
}
Read double and int from console
using System;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
(new Program()).run();
}
public void run() {
double dailyRate = readDouble("Enter your daily rate: ");
int noOfDays = readInt("Enter the number of days: ");
writeFee(calculateFee(dailyRate, noOfDays));
}
private void writeFee(double p) {
Console.WriteLine("The consultant's fee is: {0}", p * 1.1);
}
private double calculateFee(double dailyRate, int noOfDays) {
return dailyRate * noOfDays;
}
private int readInt(string p) {
Console.Write(p);
string line = Console.ReadLine();
return int.Parse(line);
}
private double readDouble(string p) {
Console.Write(p);
string line = Console.ReadLine();
return double.Parse(line);
}
}
illustrates how to read command-line arguments
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example10_4.cs illustrates how to read
command-line arguments
*/
using System;
public class Example10_4
{
public static void Main(string[] arguments)
{
for (int counter = 0; counter < arguments.Length; counter++) { Console.WriteLine("arguments[" + counter + "] = " + arguments[counter]); } } } [/csharp]