Eiffel文件读写程序调用split方法时出现参数不兼容错误求助
解决Eiffel中split方法调用的类型不匹配错误
错误原因
Eiffel的STRING.split方法要求传入的分隔符是CHARACTER类型,但你代码中传入的是双引号包裹的字符串","(STRING类型),类型不匹配导致Non-compatible actual argument错误。
修复步骤
- 修正分隔符类型:将
split(",")替换为split(',')(单引号包裹单个字符,对应CHARACTER类型)。 - 优化split调用:避免重复调用split(每次调用都会生成新的数组实例),将分割结果存储到局部变量中,提升代码效率。
- 可选:增加边界检查(防止输入行格式错误导致数组越界)。
修正后的完整代码
class PERSON_ASSISTANCE create make feature {NONE} -- Initialization make local input_file, output_file: PLAIN_TEXT_FILE id, name, birthdate, address: STRING family_members_count: INTEGER current_year, birth_year, age, financial_assistance: INTEGER line: STRING parts: ARRAY[STRING] -- 新增局部变量存储分割结果 do create input_file.make_open_read("input.txt") create output_file.make_open_write("output.txt") -- Read input file line by line current_year := 2024 from input_file.read_line until input_file.end_of_file loop line := input_file.last_string parts := line.split(',') -- 使用CHARACTER类型的分隔符 -- 可选:检查分割后的数组长度是否符合预期,避免越界 if parts.count >= 5 then id := parts.item(1) name := parts.item(2) birthdate := parts.item(3) address := parts.item(4) family_members_count := parts.item(5).to_integer -- Extract birth year and calculate age birth_year := birthdate.substring(1, 4).to_integer age := current_year - birth_year -- Calculate financial assistance financial_assistance := (age * 10) + (family_members_count * 10) -- Write result to output file output_file.put_string(id + ", " + name + ", " + financial_assistance.out + "€%N") end input_file.read_line end input_file.close output_file.close end end
额外说明
- Eiffel中,单引号
'用于表示CHARACTER,双引号"用于表示STRING,这是强类型语言的严格要求。 - 重复调用
line.split(',')会多次创建ARRAY实例,将结果存入局部变量parts可以减少不必要的内存开销和计算量。 - 新增的数组长度检查可以避免输入文件中出现格式错误的行(比如字段不足5个)导致的运行时异常。
内容的提问来源于stack exchange,提问作者Amira_AJ
相关产品推荐
相关产品推荐

