Using the INPUT statement is a rather cumbersome way of entering a single key press choice and in many cases the programmer would rather use a method that does not rely on the user pressing the enter key. For instance games require simple key presses of this sort and for this QBasic provides the INKEY$ command. Simply put the INKEY$ command returns a value from the user when a key is pressed and the value placed in the keyboard buffer. Therefore to be effective it must placed within a conditional DO LOOP UNTIL. For this example open the program from the last lesson and rename it DOLOOP and save the file. Amend the program as below.
For a full explanation of INKEY$ in relation to a DO LOOP goto
Wikibooks QBasic Advanced input
_________________________________________________
REM Simple IF THEN Selection to convert between
REM Celsius and Fahrenheit and Fahrenheit and Celsius
REM Using DO LOOP and INKEY$
DIM InputNumber AS SINGLE
DIM SelectCalc AS STRING
CLS
-----------Change the INPUT statement to a PRINT statement----------
PRINT " Please Enter C to convert from Celsius to Fahrenheit or Enter F to convert from Fahrenheit to Celcius "
--------Remove the '; SelectCalc$' from the end of the line-----
--------Add The Following Three lines-------------
DO
LET SelectCalc$ = INKEY$
LOOP UNTIL SelectCalc$ <> ""
If SelectCalc$ = "c" OR SelectCalc$ = "C" THEN
Input "Please enter the Celsius "; InputNumber
Print InputNumber ; "Celsius = " ; (InputNumber +32) * 1.8 "Fahrenheit "
END IF
IF SelectCalc$ = "f" OR SelectCalc$ = "F" THEN
Input "Please enter the Fahrenheit "; InputNumber
Print InputNumber ; "Fahrenheit = " ; (InputNumber -32) / 1.8 "Fahrenheit "
END IF
_____________________________________________
When you run the program this time the PRINT statement will Display the instructions and the DO LOOP instruction will keep repeating until a key is pressed. The Variable SelectCalc$ will contain the value of the key the user pressed and if this is 'c' or 'C' or 'f' or 'F' then the program will continue as usual otherwise the program will end.
Notice that even this is not fully error trapped because if the user enters any other key the program comes to a halt without executing any calculations. To correct this problem change the line
DO
LET SelectCalc$ = INKEY$
LOOP UNTIL SelectCalc$ <> ""
To
LOOP UNTIL SelectCalc$ = "c" OR SelectCalc$ = "C" OR SelectCalc$ = "f" OR SelectCalc$ = "F"
Now save and run the program. This time unless the user enters a an "c" or "C" or "f" or "F" the program will continue to loop.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment