提出CONSTRAINT_ERROR:josephus.adb:50索引检查失败

时间:2014-11-03 18:20:46

标签: ada josephus

我试图运行此代码,但该行出现了问题:

Soldiers (Number_Of_Soldiers) := Soldier_Type'(Name=>new String'(Line(1..Length)), Alive=>True);

有人可以帮助我吗?

非常感谢你!

--Josephus Problem

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

procedure Josephus is

    type String_Pointer is access String;

    type Soldier_Type is record
       Name  : String_Pointer;
       Alive : Boolean;
    end record;

    Max_Number_Of_Soldiers: constant := 10;
    Number_Of_Soldiers    : Integer range 0..Max_Number_Of_Soldiers := 0;

    -- start with 0 to facilitate modular arithmetic
    Soldiers: array (0..Max_Number_Of_Soldiers-1) of Soldier_Type;

    procedure Next (Index: in out Integer; Interval: Positive) is
    begin
       for I in 1..Interval loop
          loop
            Index := (Index + 1) mod Number_Of_Soldiers;
            exit when Soldiers(Index).Alive;
          end loop;
       end loop;
    end Next;

    Interval : Integer;
    Man      : Integer := Soldiers'First;

begin

     -- get interval from the standard input
     Integer_Text_IO.Get (Interval);
     Text_IO.Skip_Line;
     Text_IO.Put ("Skip every ");
     Integer_Text_IO.Put (Interval, Width=>1);
     Text_IO.Put_Line (" soldiers.");

     -- get names (one per line) from the standard input
    declare

        Line: String (1..10);
        Length: Integer;


    begin
       while not (Text_IO.End_Of_File) loop
          Text_IO.Get_Line (Line, Length);
      Soldiers (Number_Of_Soldiers) := Soldier_Type'(Name=>new String'(Line(1..Length)), Alive=>True);
          Number_Of_Soldiers := Number_Of_Soldiers + 1;
       end loop;
    end;



    for I in 1..Number_Of_Soldiers-1 loop
        Soldiers(Man).Alive := False;
        Text_IO.Put (Soldiers(Man).Name.all);
        Text_IO.Put_Line (" commits suicide.");
        Next (Man, Interval);
    end loop;

     Text_IO.Put (Soldiers(Man).Name.all);
     Text_IO.Put_Line (" is the last.");

end Josephus;

1 个答案:

答案 0 :(得分:0)

我认为您的问题在于

Max_Number_Of_Soldiers: constant := 10;

显然,指定的数字必须大于输入中可能的最大条目数!

无界输入数据集的问题是使用Ada.Containers.Vectors而不是数组的原因之一。