"ERROR: LoadError: BoundsError: attempt to access 0-element Array{Candidate,1} at index [1]" when trying to fill the empty array of a composite type

"ERROR: LoadError: BoundsError: attempt to access 0-element Array{Candidate,1} at index [1]" when trying to fill the empty array of a composite type

我在尝试使用用户输入填充空数组时出错。

const max = 9 # a maximal number of candidates

# Let us define a composite type for the candidates in our elections
mutable struct Candidate
    name::String
    votes::Int8
 end
 
 
candidates = Candidate[]

i = 1

while i < max
 println("Name of the candidate: ?")
 candidates[i].name = readline();
 println("Votes on him: ?")
 candidates[i].votes = parse(Int8, readline(), base=10);
 println("Thank you, let us move to the next candidate.")
 global i = i +1    
 end

("应聘者姓名:?")显示后,出现如下错误:

ERROR: LoadError: BoundsError: attempt to access 0-element Array{Candidate,1} at index [1]
Stacktrace:
 [1] getindex(::Array{Candidate,1}, ::Int64) at ./array.jl:731
 [2] top-level scope at /home/jerzy/ComputerScience/SoftwareDevelopment/MySoftware/MyJulia/plurality.jl:18 [inlined]
 [3] top-level scope at ./none:0
 [4] include at ./boot.jl:317 [inlined]
 [5] include_relative(::Module, ::String) at ./loading.jl:1044
 [6] include(::Module, ::String) at ./sysimg.jl:29
 [7] exec_options(::Base.JLOptions) at ./client.jl:266
 [8] _start() at ./client.jl:425
in expression starting at /home/jerzy/ComputerScience/SoftwareDevelopment/MySoftware/MyJulia/plurality.jl:16

或者,使用

candidates = Array{Candidate}(undef, 0)

而不是

candidates = Candidate[]

结果:

ERROR: LoadError: UndefRefError: access to undefined reference

作为新手,我深表歉意。我靠 what I read in this wikibook。你能推荐我多读一些书吗?

你几乎是正确的,问题是你的数组的长度是 0(你可以用 length(candidates) 验证它),所以当你试图设置数组的非零索引元素时 Julia 会抱怨candidates[i]。如果您事先不知道数组的长度,那么您应该使用 push! 函数。

const max_candidates = 9 # a maximal number of candidates

while i < max_candidates
 println("Name of the candidate: ?")
 name = readline();
 println("Votes on him: ?")
 votes = parse(Int, readline());
 push!(candidates, Candidate(name, votes))
 println("Thank you, let us move to the next candidate.")
 global i = i + 1
end

我在这里将 max 更改为 max_candidates,因为 max 会干扰基础 max 功能。

如果你知道候选人的数量,你可以使用candidates = Vector{Candidate}(undef, max_candidates)形式的初始化,注意max_candidates而不是0,因为你应该分配必要长度的向量。

candidates = Vector{Candidate}(undef, max_candidates)

for i in 1:max_candidates
 println("Name of the candidate: ?")
 name = readline();
 println("Votes on him: ?")
 votes = parse(Int, readline());
 candidates[i] = Candidate(name, votes)
 println("Thank you, let us move to the next candidate.")
end

请注意,我将 while 更改为 for 它可能对您的情况有用,也可能没有用,但至少可以让您删除 global i = i + 1 行。

如果最后一个版本适合您,那么您可以从结构定义中删除 mutable,这通常会提高性能。