似乎无法将我的数据作为整数读取并打印出来。另外,在def read (文件)函数中有一个count = aFile.gets的关闭流(IOError)。这个程序包括数组,文件和循环。这个程序的目的是获取一个数字10,并将这个数字写到一个文件中,然后在传递的每一行中,从0递增到10。
# takes a number and writes that number to a file then on each line
# increments from zero to the number passed
def write(aFile, number)
# You might need to fix this next line:
aFile.puts("number")
index = 0
while (index < number)
aFile.puts(number.to_s)
index += 1
end
end
# Read the data from the file and print out each line
def read(aFile)
# Defensive programming:
count = aFile.gets
if (is_numeric(count))
count = count.to_i
else
count = 0
puts "Error: first line of file is not a number"
end
index = 0
while (count < index)
line = aFile.gets
puts "Line read: " + line
end
end
# Write data to a file then read it in and print it out
def main
aFile = File.new("mydata.txt", "w") # open for writing
if aFile # if nil this test will be false
write(aFile, 10)
else
puts "Unable to open file to write!"
end
if aFile
read(aFile)
end
aFile.close
end
# returns true if a string contains only digits
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
发布于 2019-05-30 23:43:28
如果您想让您的代码正常工作,请更改:
aFile = File.new("mydata.txt", "w")
至:
aFile = File.new("mydata.txt", "r+")
您可以更改:
count = aFile.gets
if (is_numeric(count))
至:
count = aFile.gets.to_i
if (count.is_a?(Fixnum))
然后摆脱is_numeric?(obj)
方法。
此外,您没有递增计数器,您也可以修复它。
https://stackoverflow.com/questions/56376662
复制相似问题