Ada 引发约束_错误:josephus.adb:50索引检查失败

Ada 引发约束_错误:josephus.adb:50索引检查失败,ada,josephus,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_Pointe

我正在尝试运行此代码,但该行出现问题:

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;

我想你的问题出在线路上

Max_Number_Of_Soldiers: constant := 10;
显然,指定的数量需要大于输入中的最大可能条目数


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

索引检查失败表示数组索引超出了数组的范围。也许你的输入行比士兵阵列中的多?您的输入循环没有任何逻辑来检查输入是否过多。也许你应该在得到异常的那一行之前添加一个语句来输出士兵的数量。好的,我明白了。但是,老实说,不幸的是我不知道该怎么做<代码>文本IO.Put_行(“士兵数量=“&Integer”图像(士兵数量))。或者,如果您正在使用GNAT,
Text\u IO.Put\u行(“士兵数量=”&Number\u士兵的Img)。这不是一个正确的答案,但您实际上并没有像您在评论中所说的那样使用模块化类型。因此,您应该将士兵的数量类型声明为mod 10(在其他地方查找语法),这将影响士兵的使用、间隔、人,最重要的是士兵的数量。这可能最终会纠正您的索引问题。