我有以下代码。为了使代码正常工作,它应该读取这些行并将其写入控制台。我目前只有错误:文件的第一行不是数字。
任何可能的帮助都会很棒。
def write(aFile, number)
aFile.puts(number)
index = 0
while (index <= number)
aFile.puts(index)
index += 1
end
end
def read(aFile)
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
index += 1
end
end
def main
aFile = File.new("mydata.txt", "w")
if aFile
write(aFile, 10)
aFile.close
aFile = File.new("mydata.txt", "r")
read(aFile)
aFile.close
else
puts "Unable to open file to write or read!"
end
end
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
答案 0 :(得分:1)
请检查以下内容,
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
当您读取文件行时,您总是读取文本/字符串中的行(甚至文件中的数字)。因此,您始终处在else块中。