BASIC stamp manual v2.2
SELECT...CASE – BASIC Stamp Command Reference
Page 390 • BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com
Higher.” then continues after the ENDSELECT, displaying “Try again: “
on the screen and giving the user another guess. If guess is greater than
140, the second CASE is true, “Too high.” will be displayed followed by
“Try again: “, etc. If the user guesses 123, they are congratulated and the
program stops.
You may have noticed a potential error in the code: both of the last two
CASEs are true if guess is 123. So why didn’t the second CASE execute?
The answer is because only the first “true” case is executed and any
further cases are ignored. If we had swapped the order of the last two
cases, we’d have a bug in the program and the user would never find out
that 123 was the correct number because “CASE 123” would never have
been evaluated. It’s not recommend to write code this way; “CASE 121
TO 122, 124 TO 125” or even “CASE 121, 122, 124, 125” would have been
more clear and would prevent potential bugs like this one.
Many situations call for special handling of a few cases and every other
case is handled another way. There is a special form of CASE to handle
this as well, called CASE ELSE. In our example above, we could have
replaced “CASE 121 TO 125” with “CASE ELSE” and it would behave
exactly the same. CASE ELSE is a way to ensure that every possible
Expression value is handled by a case; it’s like saying, “If none of the
previous cases were true, run this case.” For a SELECT…CASE statement
to work properly, it must have no more than one CASE ELSE statement,
and that CASE ELSE statement must be the very last CASE.
The Condition(s) have a format similar to that of the IF…THEN commands
except, in SELECT…CASE statements, Expression is always implied as the
first part of the condition.
Demo Program (SELECT-CASE.bs2)
' SELECT-CASE.bs2
' This program generates a series of 16-bit random numbers and tests each
' to determine odd or even, and where it falls in the possible range:
' lower third, middle third, or upper third. The program is useful for
' testing various seed values for RANDOM.
' {$STAMP BS2}
' {$PBASIC 2.5}
All
2
NOTE: This example program can be
used with all BS2 models by changing
the $STAMP directive accordingly.