using System;
class IfSelect {
public static void Main() {
string myInput;
int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
// Single Decision and Action with brackets
if (myInt > 0) {
Console.WriteLine("Your number {0} is greater than zero.", myInt);
}
// Single Decision and Action without brackets
if (myInt < 0)
Console.WriteLine("Your number {0} is less than zero.", myInt);
// Either/Or Decision
if (myInt != 0) {
Console.WriteLine("Your number {0} is not equal to zero.", myInt);
}
else {
Console.WriteLine("Your number {0} is equal to zero.", myInt);
}
// Multiple Case Decision
if (myInt < 0 || myInt == 0) {
Console.WriteLine("Your number {0} is less than or equal to zero.", myInt);
}
else if (myInt > 0 && myInt <= 10) {
Console.WriteLine("Your number {0} is between 1 and 10.", myInt);
}
else if (myInt > 10 && myInt <= 20) {
Console.WriteLine("Your number {0} is between 11 and 20.", myInt);
}
else if (myInt > 20 && myInt <= 30) {
Console.WriteLine("Your number {0} is between 21 and 30.", myInt);
}
else {
Console.WriteLine("Your number {0} is greater than 30.", myInt);
}
}
}
說明
1.清單3-1中的IF語句的各種格式都使用了同一個輸入變數"myInt"。
這是從使用者獲得互動內容的另一種方式。我們首先輸出一行資訊:"Please enter a number:"到控制台。"Console.ReadLine()"語句使得程式等待來自使用者的輸入,一旦使用者輸入一個數字,按斷行符號鍵之後,該數字以字串的形式返回到"myInput"變數中,由於我們需要的是一個整數,所以需要轉換變數"myInput"成整型資料。用命令"Int32.Parse(myInput)"即可完成。 (Int32 等資料類型將在後面的課程中加以介紹。) 轉換結果放到"myInt"變數中,這是個整數類型。
2.有了我們所需要的類型的資料,就可以用"if"語句來進行條件判斷了。
對於第一種形式的IF語句,格式為: if (boolean expression) { statements }。該語句必須以關鍵字"if"開始。之後,括弧中為布林運算式。該布林運算式必須計算出一個true或者false值。在本例中,我們檢查使用者的輸入,看看輸入值是否大於0,如果運算式運算結果為true,就執行大括弧中的語句。(我們把大括弧之間的語句部分稱為"block"。) 塊中有一個或者多個語句。如果布林運算式的值為false,我們就忽略塊中的語句,直接執行塊後面的語句。
using System;
class SwitchSelect {
public static void Main() {
string myInput;
int myInt;
begin:
Console.Write("Please enter a number between 1 and 3: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
// switch with integer type
switch (myInt) {
case 1:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 2:
Console.WriteLine("Your number is {0}.", myInt);
break;
case 3:
Console.WriteLine("Your number is {0}.", myInt);
break;
default:
Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);
}
decide:
Console.Write("Type \"continue\" to go on or \"quit\" to stop: ");
myInput = Console.ReadLine();
// switch with string type
switch (myInput) {
case "continue":
goto begin;
case "quit":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("Your input {0} is incorrect.", myInput);
goto decide;
}
}
}