Question

I am a beginner in Ada programming and I have the following code :

PROCEDURE ask(variable: OUT myType) IS
BEGIN
   Put("Enter : ");
   Get(variable);
   Skip_Line;
EXCEPTION
   WHEN OTHERS => RAISE wrongInput;
END ask;

This procedure asks to enter something and put it in my "variable" variable (which type is myType containing characters from '1' to '3').

I raise an exception when the input is not correct.

Now I would like to do something else when the input is 'm' for example.

How could I do this?

Was it helpful?

Solution 2

This answer is based on the assumption that myType is declared as something like

subtype myType is Character range '1' .. '3';

You can write the output into an unconstraint Character variable, then check it:

PROCEDURE ask (variable : OUT myType) IS
   Input : Character;
BEGIN
   Put ("Enter : ");
   Get (Input);
   Skip_Line;
   CASE Input IS
      WHEN 'm' =>
         RAISE gotM;
      WHEN OTHERS =>
         -- this will raise Constraint_Error if the value is not
         -- in range '1' .. '3'
         variable := Input;
   END CASE;
EXCEPTION
   WHEN OTHERS => RAISE wrongInput;
END ask;

I used case instead of a simple if because it sounds like there may be other input values added in the future. Now while this is technically possible, I consider it bad style, because it uses the exception gotM for implementing non-exceptional behavior. You should re-think your code layout so that you don't have a procedure ask that can only return '1' .. '3' but needs to handle other input, too.

OTHER TIPS

Change the declaration of myType:

type myType is ('1', '2', '3', 'm');

Something like this, perhaps? (just guessing here, "I would like to do something else" is extremely vague).

procedure Ask (Variable : out My_Type) is
begin
   loop
      begin
         Put ("Enter :");
         Get (Variable);
         Skip_Line;
         return;
      exception
         when others =>
            Skip_Line;
            Put_Line ("invalid.");
      end;
   end loop;
end Ask;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top