Câu lệnh điều kiện
u lnh điều kiện
u lnh điều kiện if :
Cú pháp như sau:
if (condition)
statement(s)
[else
statement(s)]
Xét ví dụ sau:
Nếu nhiều n một câu lệnh để thi hành trong u điều kiện chúng ta sẽ
đưa tất cả các câu lệnh này vào trong du ngoặc móc ({ ... }) ging như ví d
dưới đây
bool isZero;
if (i == 0)
{
isZero = true;
Console.WriteLine("i is Zero");
}
else
{
isZero = false;
Console.WriteLine("i is Non-zero");
}
Đoạn code trên kiểm tra isZero có bng 0 hay không.
Xét ví dụ:
Trong ddưới đây chúng ta dùng u điều kiện íf . . . else để kiểm tra
nhiều điều kiện .
using System;
namespace Wrox.ProCSharp.Basics
{
class MainEntryPoint
{
static void Main(string[] args)
{
Console.WriteLine("Type in a string");
string input;
input = Console.ReadLine();
if (input == "")
{
Console.WriteLine("You typed in an empty string");
}
else if (input.Length < 5)
{
Console.WriteLine("The string had less than 5 characters");
}
else if (input.Length < 10)
{
Console.WriteLine("The string had at least 5 but less than 10
characters");
}
Console.WriteLine("The string was " + input);
}
}
}
Download Conditional
Đoạn code trên không giới hạn bao nhiêu else if's trong câu điều kiện
if (i == 0)
Console.WriteLine("i is Zero"); // câu lnh chỉ thi hành khi i == 0
Console.WriteLine("i can be anything"); // câu lệnh thi hành bt kì giá tr
của i
u lnh switch
Các câu lệnh if nm lồng rất kđọc, khó gỡ rối. Khi bạn một loạt
lựa chọn phức tạp thì nên sử dụng câu lệnh switch.
pháp như sau:
switch (biểu thức)
{ casce biểu thức ràng buộc:
câu lệnh
câu lệnh nhảy
[default: câu lệnh mặc định]
}
Thí dsau: Tdsẽ kiểm tra integerA thoả đúng trong c trường hợp 1,
2, 3 không nếu không đúng sẽ thực thi trường hợp default
switch (integerA)
{
case 1:
Console.WriteLine("integerA =1");
break;
case 2:
Console.WriteLine("integerA =2");
break;
case 3:
Console.WriteLine("integerA =3");
break;
default:
Console.WriteLine("integerA is not 1,2, or 3");
break;
}
Xem các T dụ sau để hiểu rõ thêm về switch:
// assume country and language are of type string
switch(country)