最近小菜蟲還是秉承實踐出真理的方式學習C#,親自把一段段代碼敲出來,纔有些感覺。
下面是學習C#語句過程中敲的例子,有選擇語句,迭代語句,跳轉語句,異常處理語句。
一個個都是在打包,下面開始從例子開始語法吧!
//if-else語句的用法
bool flag =false ;
if (flag == true)
{
Console.WriteLine("The flag is true.");
}
else
{
Console.WriteLine("The flag is false.");
}
Console.Read();
//if-else多分支結構
Console.WriteLine("輸出結果爲:");
char c = 'D';
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("這是一個小寫字母");
}
else
{
Console.WriteLine("這是一個大寫字母");
}
//else if 階梯語句的使用
Console.WriteLine("輸出結果爲:\n");
char c = 'A';
if(Char.IsUpper (c))
{
Console.WriteLine(c+"爲大寫字母");
}
else if(Char.IsLower(c))
{
Console.WriteLine(c+"爲小寫字母");
}
else if(Char.IsDigit (c))
{
Console.WriteLine("請輸入有效字符");
}
Console.ReadLine (); }
else
{
Console.WriteLine("這不是字母");
}
Console.ReadLine();
//利用空case語句檢查數字在什麼範圍內
Console.WriteLine("輸出結果爲:\n ");
int n = 1;
switch (n)
{
case 1:
case 2:
case 3:
Console.WriteLine("不能確定輸入的是1,2,3");
break;
default :
Console.WriteLine("不能確定輸入值的範圍");
break; }
Console.ReadLine();
//case標籤內使用goto語句跳轉到另一個case標籤,判斷用戶輸入的值,進而完成費用的計算。
Console.WriteLine("輸出結果爲:\n選對號碼:1=小 2=大 3=很大");
Console.Write("請輸入你的選擇:");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;
switch (n)
{
case 1:
cost+=25;
break;
case 2:
cost+=25;
goto case 1;
case 3:
cost+=50;
goto case 1;
default :
Console.WriteLine("請按要求輸入信息");
break; } if (cost!= 0)
{
Console.WriteLine("應付費用爲{0}",cost );
}
Console.Read();
//利用while語句循環輸出5個數字
Console.WriteLine("輸出結果爲:");
int n = 1;
while (n < 6)
{
Console.WriteLine("循環第{0}次",n);
n++;
}
Console.Read();
//利用do-while語句循環的流程
Console.WriteLine("輸出結果爲:");
int n = 1;
do
{
Console.WriteLine("循環{0}次", n);
n++;
}
while (n < 0);
Console.Read();
//for語句的使用
for (int i = 0, j = 10; i <= j; i++, j--)
{
Console.WriteLine("{0},{1}",i,j);
}
Console.Read();
//利用foreach輸出整數數組的內容
Console.WriteLine("輸出結果:");
int[] fibarray = new int[] { 0, 1, 2, 3, 5 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i); }
Console.Read();
//break語句在計數達到4後終止循環
Console.WriteLine("輸出結果爲:");
for (int i = 1; i <= 10; i++)
{
if (i > 4)
{
break;
}
Console.WriteLine(i);
}
Console.Read();