尝试使用用户的输入填充空数组时出现错误。
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
很抱歉是这样的新手。我依靠我在这本维基教科书中读到的内容。你能推荐我更多的阅读吗?
你几乎是对的,问题是数组的长度是0(你可以用length(candidates)
验证它(,所以当你试图用candidates[i]
数组设置非零索引元素时,Julia 会抱怨。如果你事先不知道数组的长度,那么你应该使用 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
,它通常对性能更好。