gpt4 book ai didi

arrays - "ERROR: LoadError: BoundsError: attempt to access 0-element Array{Candidate,1} at index [1]"尝试填充复合类型的空数组时

转载 作者:行者123 更新时间:2023-12-03 23:06:10 25 4
gpt4 key购买 nike

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

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) 验证它),所以当你试图用 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
我这里换了 maxmax_candidates因为 max干扰 Base 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
请注意,我更改了 whilefor它可能对您的情况有用也可能没有用,但至少可以让您删除 global i = i + 1线。
如果最后一个版本适合您,那么您可能可以删除 mutable从结构定义来看,它通常对性能更好。

关于arrays - "ERROR: LoadError: BoundsError: attempt to access 0-element Array{Candidate,1} at index [1]"尝试填充复合类型的空数组时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62550582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com