Home [C# 筆記] do-while
Post
Cancel

[C# 筆記] do-while

  • while
    先判斷,再執行。有可能一遍迴圈都不執行。

  • do-while
    先執行,再判斷。最少執行一遍迴圈。

範例:唱歌唱到老師滿意為止才能回家 (do-while)

明天小明就要登台演出了,老師說再把明天的演出歌曲唱一遍, 如果滿意,小明就可以回家了,否則就需要再練習一遍,直到老師滿意為止。

1
2
3
4
5
6
7
8
9
10
//循環體:小明唱了一遍,問老師:滿意嗎?老師回答
//循環條件:老師不滿意

string answer;
do
{
    Console.WriteLine("老師,我唱的你滿意嗎? yes/no");
    answer = Console.ReadLine()!;
} while (answer == "no");
Console.WriteLine("OK, 放學回家~");

遇見這種或先執行一遍的迴圈,拿著執行後的結果再去判斷是否執行迴圈的循環,推薦使用do-while迴圈。

如果是用while撰寫,就變成有重複代碼

1
2
3
4
5
6
7
8
Console.WriteLine("老師我唱的歌曲,你滿意嗎?(yes/no)");
string answer = Console.ReadLine();

while (answer == "no")
{
    Console.WriteLine("老師我再唱一遍,你滿意嗎?");
    answer = Console.ReadLine();
}

範例:要求用戶輸入帳號密碼,只要不是admin, 8888就一直提示帳號碼密錯誤,請重新輸入

1
2
3
4
5
6
7
8
9
10
11
12
string username;
string password;
do
{
    Console.WriteLine("請輸入帳號");
    username = Console.ReadLine();
    Console.WriteLine("請輸入密碼");
    password = Console.ReadLine();

} while (username != "admin" || password != "8888");
Console.WriteLine("登入成功");
Console.ReadKey();

練習:不斷要求用戶輸入學生姓名,輸入q結束

1
2
3
4
5
6
string name;
do
{
    Console.WriteLine("請輸入學生姓名,輸入q結束");
    name = Console.ReadLine();
} while (name!="q");

while 寫的話

1
2
3
4
5
6
string name = "";
while (name != "q")
{
    Console.WriteLine("請輸入學生姓名");
    name = Console.ReadLine();
}
This post is licensed under CC BY 4.0 by the author.