Jer*_*ska 5 arrays composite julia
尝试使用用户的输入填充空数组时出现错误。
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
Run Code Online (Sandbox Code Playgroud)
显示(“候选人姓名:?”)后,出现以下错误:
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
Run Code Online (Sandbox Code Playgroud)
或者,使用
candidates = Array{Candidate}(undef, 0)
Run Code Online (Sandbox Code Playgroud)
代替
candidates = Candidate[]
Run Code Online (Sandbox Code Playgroud)
结果是:
ERROR: LoadError: UndefRefError: access to undefined reference
Run Code Online (Sandbox Code Playgroud)
很抱歉成为这样的新手。我依赖于我在这本维基书中读到的内容。你能让我再读一些书吗?
你几乎是正确的,问题是你的数组的长度是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
Run Code Online (Sandbox Code Playgroud)
我已将此处更改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
Run Code Online (Sandbox Code Playgroud)
请注意,我while对其进行的更改for可能对您的情况有用,也可能没有用,但至少可以让您删除global i = i + 1行。
如果最后一个版本适合您,那么您可能可以mutable从结构定义中删除,这通常对性能更好。