我前几天在这里发布了,因为我对Fortran的语法感到困惑,并得到了很多帮助。但是现在我被困在同一个泡菜中,但这次和阿达在一起。
以下是我的计划的要点。我正在尝试从用户那里读取一个句子并将其中的每个字符转换为莫尔斯码。
with Ada.Text_IO;
with Ada.Strings;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded;
with Ada.Command_Line;
use Ada.Text_IO;
procedure MorseCode is
tempSentence : array(1 .. 20) of string;
last : Integer;
size : Integer;
i : Integer;
begin
Put("Enter the size of your sentence: ");
Get(size);
Put("Enter the sentence you would like to convert to morse code: ");
Get_Line(tempSentence, last);
Put_Line(tempSentence);
While_Loop :
while i < size loop
if tempSentence(i .. i) = 'A' or tempSentence(i) = 'a' then
Put(".- ");
elsif tempSentence(i .. i) = 'B' or tempSentence(i) = 'b' then
Put("-... ");
elsif tempSentence(i) = 'C' or tempSentence(i) = 'c' then
Put("-.-. ");
end if;
end loop While_Loop;
end;
答案 0 :(得分:0)
我可能不应该,但这里的问题远远超出了简单的语法错误,所以这里有一些指向更像Ada的方法。
大胆的单词值得在一本好的Ada书中更详细地阅读。
首先,停止思考这么低的水平。 字符串是字符数组,而Ada中的数组提供了数组属性等功能,使编程更简单 - 尤其是程序维护。
创建数组时,数组的长度是固定的,但在此之前不必确定该长度。所以你可以声明一个数组并用函数调用初始化它 - 它从函数调用的结果中获取它的大小。
使用此工具并将size
完全取消。
当声明块结束时,数组超出范围,因此它会自动释放,如果它在循环中,则函数调用可以返回不同大小的字符串,因此数组边界每次都可以不同 - 问题
我们需要循环遍历数组中的所有字符,但我们不知道它的大小...所以只需询问它,例如通过其范围属性。
而不是每次测试两次,使用Ada.Characters.Handling
包中的函数来确保我们只处理小写。
此外,如果语句是此任务的不良选择, case 语句更简单,更短 - 我已在下面显示
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Characters.Handling;
procedure MorseCode is
begin
Put("Enter the sentence you would like to convert to morse code: ");
declare
Sentence : String := Get_Line;
begin
Put_Line(Sentence);
for i in Sentence'range loop
if Ada.Characters.Handling.To_Lower(Sentence(i)) = 'a' then
Put(".- ");
-- elsif etc ... not very nice
end if;
case Ada.Characters.Handling.To_Lower(Sentence(i)) is
when 'b' => Put("-...");
when 'c' => Put("-.-.");
when others => null;
end case;
end loop;
end;
end;
在这个简单的示例中,您还不需要有界和无界字符串。它们有时候使用起来有点乏味,你需要在它们和简单的字符串之间进行类型转换。