The case-else Statement


Just like the if-then statement, the case statement can have the else section to cover any condition not tested before. The syntax of the case-else statement is:

case expression of   case_1: statement_1;   case_n: statement_n;   else     else_statement; end;

The else section can also have its own block:

case expression of   case_1: statement_1;   case_n: statement_n;   else begin     else_statement;   end; end; 

The syntax requirements of the else keyword are different in the if-then-else and case-else statements. In the if-then-else statement, the semicolon is not allowed before the else keyword, while in the case-else statement it is.

Listing 3-14: The case-else statement

image from book
var   x: Integer; begin   ReadLn(x);   case x of     1: WriteLn('Gold');     2: WriteLn('Silver');     3: WriteLn('Bronze');     else       WriteLn('No medal for you.');   end;   ReadLn; end.
image from book

You can also nest case statements and, if you do so carefully, you can increase the speed of your application even further. We can modify the application that displays the names of the months by using two case statements. The outer case statement checks if the number is in the 1 to 12 range, and the inner case statement displays month names. This solution is displayed in Listing 3-15.

Listing 3-15: Nested case statements

image from book
program Project1; {$APPTYPE CONSOLE} uses   SysUtils; var   monthNum: Integer; begin   Write('Enter a number from 1 to 12: ');   ReadLn(monthNum);   case monthNum of     1..12: begin       case monthNum of         1: WriteLn('January');         2: WriteLn('February');         3: WriteLn('March');         4: WriteLn('April');         5: WriteLn('May');         6: WriteLn('June');         7: WriteLn('July');         8: WriteLn('August');         9: WriteLn('September');         10: WriteLn('October');         11: WriteLn('November');         12: WriteLn('December');       end; // inner case     end;      // 1..12     else       WriteLn(monthNum, ' is not a valid number.');   end;       // outer case   ReadLn; end.
image from book



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net