D(程式語言)/d2/條件語句和迴圈
條件語句和迴圈對於編寫 D 程式至關重要。
module palindromes;
import std.stdio;
bool isPalindrome(string s)
{
int length = s.length;
int limit = length / 2;
for (int i = 0; i < limit; ++i)
{
if (s[i] != s[$ - 1 - i])
{
return false;
}
}
return true;
}
void main()
{
string[] examples = ["", "hannah", "socks", "2002", ">><<>>", "lobster"];
foreach(e; examples)
{
if(!e.length) continue; // skip that empty string
if(isPalindrome(e))
writeln(e, " is an example of a palindrome.");
else
writeln(e, " is an example of what's not a palindrome.");
}
while(true)
{
write("Type any word: ");
string input = readln();
if(input.length <= 1) // length == 1 means input == "\n"
break; // nothing was typed
input = input[0 .. $-1]; // strip the newline
if(isPalindrome(input))
writeln(input, " is a palindrome.");
else
writeln(input, " is not a palindrome.");
}
}
import std.stdio;
string analyzeHoursOfSleep(int hours)
{
if(!hours) return "You didn't sleep at all.";
string msg = "";
switch(hours)
{
case 1,2,3:
msg ~= "You slept way too little! ";
goto case 7;
case 4: .. case 6:
msg ~= "Take a nap later to increase alertness. ";
case 7:
msg ~= "Try to go back to sleep for a bit more. ";
break;
default:
msg ~= "Good morning. Grab a cup of coffee. ";
}
return msg ~ '\n';
}
void main()
{
writeln(analyzeHoursOfSleep(3));
writeln(analyzeHoursOfSleep(6));
writeln(analyzeHoursOfSleep(7));
writeln(analyzeHoursOfSleep(13));
int i = 0;
L1: while(true)
{
while(true)
{
if(i == 3)
break L1;
i++;
break;
}
writeln("Still not out of the loop!");
}
}
/*
Output:
You slept way too little! Try to go back to sleep for a bit more.
Take a nap later to increase alertness. Try to go back to sleep for a bit more.
Try to go back to sleep for a bit more.
Good morning. Grab a cup of coffee.
Still not out of the loop!
Still not out of the loop!
Still not out of the loop!
*/
使用 if 允許您只在滿足特定條件時執行程式碼的一部分。
if(condition that evaluates to true or false)
{
// code that is executed if condition is true
} else {
// code that is executed if condition is false
}
事實上,如果 if 或 else 中的程式碼段只有一行長,則可以省略花括號。
if(condition1) do_this();
else if(condition2) do_that(); // only executed if condition1 is false, but
// condition2 is true
else do_the_other_thing(); // only executed if both condition1 and condition2 are false
因此,這經常被看到
if (condition1) {
do_something1();
something_more1();
} else if(condition2) {
do_something2();
something_more2();
} else if(condition3) {
do_something3();
something_more3();
} else if(condition4) {
do_something4();
something_more4();
} else {
do_something_else();
}
放在 if 等條件語句中的括號內的條件可以是任何可以轉換為 bool 的值。這包括整型和浮點型(非零值為 true,否則為 false)以及指標(null 為 false)和動態陣列(始終為 true)。
while 迴圈允許您重複執行程式碼塊,直到滿足特定條件為止。while 迴圈有兩種形式
while(condition1) {
do_this();
}
和
do {
do_this();
} while(condition1)
區別在於,在第一個示例中,如果 condition1 為假,則不會呼叫 do_this,而在第二個示例中,它將被呼叫一次(條件檢查發生在程式碼執行一次之後)。
此迴圈用於 迭代。看看使用 foreach 的兩種方法
foreach(i; [1,2,3,4]) {
writeln(i);
}
foreach(i; 1 .. 5) { writeln(i); } // equivalent to above
這種型別的迴圈是最複雜的,但它也是最能控制的。它與其他類 C 語言的定義方式相同
for(initialization; condition; counting expression) { ... }
初始化 表示式僅在開頭執行一次。然後檢查 condition 是否為 true 或 false。如果為 true,則執行條件塊內的程式碼(括號內的程式碼)。執行完該程式碼後,將執行 計數表示式。然後,檢查 condition,如果為 true,則繼續迴圈。例如
for(int i=0; i <= 5; i++)
{
write(i);
}
// output: 012345
您甚至可以省略 for 括號內的部分內容。以下兩者是等價的
for(int i=0; i==0; ) {
i = do_something();
}
int i = 0;
while(i == 0) {
i = do_something();
}
這是兩種在迴圈中使用的語句。
break 語句會跳出迴圈。每當遇到 break 語句時,迴圈會立即退出。此語句可以放在 while、for、foreach 和 switch 塊內(您將在後面學習這些塊)。
continue 語句會導致迴圈從開頭重新開始。讓我們透過程式碼看看它是如何工作的。此程式碼示例計算到 7,但跳過 5。
for(int i = 0; i <= 7; i++)
{
if(i == 5) continue;
writeln(i);
}
D 允許使用標籤和 goto 進行絕對分支。
int i = 0;
looper: // this is a label
write(i);
i++;
if(i < 10) goto looper;
writeln("Done!");
// 0123456789Done!
除非必須,否則不要使用它們。使用標籤的程式碼通常可以用更易讀的迴圈結構(如 for、while 和 foreach)來編寫。
D、C 和 C++ 中有一個叫做 switch 的東西。D 的 switch 實際上比 C 和 C++ 的 switch 更強大。
switch(age)
{
case 0,1: // if(age == 0 || age == 1) { ... }
writeln("Infant");
break;
case 2,3,4: // else if (age == 2 || age == 3 || age == 4) { .. }
writeln("Toddler");
break;
case 5: .. case 11:
writeln("Kid");
break;
case 12:
writeln("Almost teen");
break;
case 13: .. case 19:
writeln("Teenager");
break;
default: // else { .. }
writeln("Adult");
}
請注意,您必須使用 break 才能跳出 switch。否則,會發生 貫穿。此外,您可以使用 goto。
int a = 3;
switch(a)
{
case 1:
writeln("Hello");
case 2:
writeln("Again");
break;
case 3:
goto case 1;
default:
writeln("Bye");
}
/* output: Hello
Again
*/
字串可以在 case 中使用。這是 C 或 C++ 中沒有的功能。
(它似乎在最近的編譯器中不起作用)。
您也可以對 foreach、while 和 for 迴圈使用 else。如果這些迴圈中的任何一個都有一個 else 子句,那麼只有當迴圈正常終止(即不使用 break)時,才會執行 else。
int[] arr = [1,2,3,5,6];
foreach(item; arr)
{
if(item == 4) break;
}
else
{
writeln("No four found.");
}
//Output: No four found.