That last program works great, as long as the user always
types in a lowercase "y". What happens if the user types
in "yes"? Since "yes" is not the same as "y" to the computer,
the test for Answer$="y" will fail, and the program will
end. Probably not a good idea. We have the same problem
if our user enters a capital "Y". Try a few of these to
see what I mean.
There are several ways to make this program smarter and
easier to use for our users.
We could have it check for a few different ways of saying
yes by using "OR", like this:
CLS DO INPUT "Enter the first number: ", A INPUT "Enter the second number: ", B PRINT "The answer is: "; A * B
INPUT "Would you like to do it again (y/n)? ", Answer$ LOOP WHILE Answer$="y" OR Answer$="Y"
This version will allow the user to enter "y" or
"Y" and the program will run again. We can get even
more clever by using LEFT$ like this:
CLS DO INPUT "Enter the first number: ", A INPUT "Enter the second number: ", B PRINT "The answer is: "; A * B
INPUT "Would you like to do it again? ", Answer$ FirstLetter$ = LEFT$(Answer$, 1) LOOP WHILE FirstLetter$="y" OR FirstLetter$="Y"
This version will let the user enter "Yes", "yes", or just
about anything that starts with a "y" because LEFT$ is
used to only look at the first character in their answer.
You could even enter "yep" or "YEAH!" and the program
will begin again.
This may seem to make the computer
smarter, but we know what's really going on. To prove
the computer really isn't very smart, try entering "sure"
or "yellow". It thinks "sure" is "no", and "yellow" is
"yes".
LEFT$
LEFT$ can be used to take a certain number of
letters from the left side of a string variable.
As an example, if we have:
A$="TEST"
Then LEFT$(A$,2) will give us "TE". LEFT$(A$,3)
will give us "TES". The first "parameter" you pass
to LEFT$ is the string you want to work with.
The second parameter you pass to LEFT$ is the
number of characters (letters) you want. Let's
try a program that uses LEFT$ in a different way:
INPUT "Enter something:", A$ PRINT A$ PRINT LEFT$(A$,1) PRINT LEFT$(A$,2) PRINT LEFT$(A$,3)
This program will print the first character of whatever
you enter, followed by the first two characters, followed
by the first three characters:
Enter something: Jack Jack J Ja Jac
QBASIC also provides a RIGHT$() in case you were
curious, and it works just like LEFT$(). Try this:
INPUT "Enter something:", A$ PRINT A$ PRINT RIGHT$(A$,1) PRINT RIGHT$(A$,2) PRINT RIGHT$(A$,3)
Here's an example of what that program will do:
Enter something: Jack Jack k ck ack
Source: http://jpsor.ucoz.com |