Bài 4: Các cấu trúc điều khiển - Pdf 13


LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG
Bài 4 Các cấu trúc điều khiển
Nội dung
Cấu trúc chọn lựa
Cấu trúc lặp

Câu lệnh lựa chọn
Có 2 nhóm lệnh
-
Lệnh if : dùng để thực hiện code dựa trên 1 điều
kiện Boolean
-
Lệnh switch : dùng để thực hiện code dựa trên 1
giá trị

Câu lệnh if
Cú pháp
if (expression)
statement1;
[else
statement2;]

Câu lệnh if
if (expression)
{
statement1;
statement2;
}

using System;


Câu lệnh if ….else…….
using System;
namespace Example2
{
class NumberGame
{
static void Main()
{
int number = 5;
string userGuess;
int guess;
Console.WriteLine("I am thinking of a number between
1 and 10");

Console.Write("Please enter your guess: ");
userGuess = Console.ReadLine();
guess = Convert.ToInt32(userGuess);
if (number == guess)
{
Console.WriteLine("Incredible, you are correct");
}
else
{
Console.WriteLine("Sorry Chump");
}
}
}
}



Ví dụ
using System;
class TestStr
{
const string CPlusPlus = “C++”;
const string VisualBasic = “Visual Basic”;
const string Java = “Java”
public static void Main()
{

Console.WriteLine(“What is your prefer language (exclude
C#) : “);
string inputStr = Console.ReadLine();
if ( 0 = = String.Compare(inputStr,CPlusPlus,true))
Console.WriteLine(“No problem with C#”);
if ( 0 = = String.Compare(inputStr,Java,true))
Console.WriteLine(“Not easier than C#”);
………………………………

Tìm hiểu
Phương thức tĩnh String.Compare
Có 6 cách sử dụng (overload)

String.Compare trả về -1 nếu chuỗi đầu tiên nhỏ hơn chuỗi
thứ hai.Trả về 1 nếu chuỗi đầu tiên lớn hơn chuỗi thứ hai và
trả về 0 nếu 2 chuỗi bằng nhau

Phương thức CompareTo của 1 biến kiểu string


int guess;
Console.WriteLine("I am thinking of a number between 1 and 10");
Console.Write("Please enter your guess: ");
userGuess = Console.ReadLine();
guess = Convert.ToInt32(userGuess);
if (number == guess)
{
Console.WriteLine("Incredible, you are correct");
}
else if (guess > number)
{
Console.WriteLine("Lower, try again");
}
else //guess must be too low
{
Console.WriteLine("Higher, try again");
}
}
}
}

Bài tập
Viết chương trình cho phép NSD đoán ngày sinh
của bạn. Sử dụng cấu trúc chọn lựa nhằm thực
hiện các yêu cầu sau
-
Nếu dữ liệu nằm ngoài phạm vi từ 1 đến 31 thì
thông báo lỗi
-
Nếu NSD đoán sai thì thông báo : “Lớn hơn” hay

Console.WriteLine("Please guess the day of
my birth, from 1 to 31");
Console.Write("Please enter your guess: ");

userGuess = Console.ReadLine();
guess = Convert.ToInt32(userGuess);
if (guess < 0)
{
Console.WriteLine("Months don't have
negative days, Einstein");
}
else if (guess > 31)
{
Console.WriteLine("Pretty long month,
genius");
}
else if (guess == myBirthday)
{
Console.WriteLine("Incredible, you are
correct");
}


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status