ada

How to add < and > check in case ... when?


I'm new to Ada programming language and working on an exercise,

The instructions are as follows,

• Write a case statement with 4 alternatives that displays information on a roll of a pair of dice.
– A winning roll (7 or 11)
– A losing roll (2 or 3 or 12)
– A point roll (4 or 5 or 6 or 8 or 9 or 10)
– An invalid roll (less than 2 or greater than 12)
• Use the others option for the point roll
– In reality, I’d use the others option for invalid rolls
– The expressions Integer’First and Integer’Last yield the smallest possible (most negative) integer and largest possible integer.

I could come-up with following code but can't figure out how to handle An invalid roll case, I tried searching online, reading the docs.adacore.com but couldn't find anything that help me understand

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Learning is
    Dice : Integer; -- the value of a roll
begin
    Put_Line ("Enter the value of your roll of the dice");
    Get (Dice);
    New_Line;
    Put("The number ");
    Put(Item => Dice, Width => 0);
    case Dice is
        when 7 | 11 =>
            Put_Line ("is a winning dice roll");
        when 2 | 3 | 12 =>
            Put_Line ("is a losing dice roll");
        when TBD =>
            Put_Line ("is not a valid dice roll");
        when others =>
            Put_Line ("establishes the point");
    end case;
    New_Line;
end Learning;

I'm using JDoodle to compile my program.


Solution

  • As you are required to use a case statement, but forbidden to use the others clause to catch an invalid roll, examine what other ways you can specify a discrete choice. Among the options available, a range seems promising, as it permits the use of the scalar type attributes mentioned in the problem statement.

    when Integer'First .. 1 | 13 .. Integer'Last =>
       Put_Line (" is not a valid dice roll");
    

    Addendum: As an alternative, also consider a subtype indication.

    subtype Below_2 is Integer range Integer'First .. 1;
    subtype Above_12 is Integer range 13 .. Integer'Last;
    …
    when Below_2 | Above_12 =>
       Put_Line (" is not a valid dice roll");