Reputation: 11
I wrote the following code to read from a file and print out the output in the terminal. I am getting output but instead of it printing out once like:
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
I am getting the output twice like:
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav
Any ideas why that might be?
This is my code:
class Track
attr_accessor :name, :location
def initialize (name, location)
@name = name
@location = location
end
end
# Returns an array of tracks read from the given file
def read_tracks(a_file)
count = a_file.gets().to_i()
i=0
tracks = Array.new()
while (i<count)
track = read_track(a_file)
tracks << track
i+=1
end
return tracks
end
# reads in a single track from the given file.
def read_track(a_file)
track_name=a_file.gets.chomp
track_location = a_file.gets.chomp
track = Track.new(track_name, track_location)
track.name= track_name
track.location= track_location
return track
end
# Takes an array of tracks and prints them to the terminal
def print_tracks(tracks)
index = 0
while (index<tracks.length)
print_track tracks[index]
index+=1
end
end
# Takes a single track and prints it to the terminal
def print_track(track)
puts(track.name)
puts(track.location)
end
# Open the file and read in the tracks then print them
def main()
a_file = File.new("input.txt", "r") # open for reading
tracks=read_tracks(a_file)
print_tracks(tracks)
# Print all the tracks
print_tracks(tracks)
end
main()
Upvotes: 0
Views: 158
Reputation: 337
You are calling print_tracks()
twice in here
# Open the file and read in the tracks then print them
def main()
a_file = File.new("input.txt", "r") # open for reading
tracks=read_tracks(a_file)
print_tracks(tracks)
# Print all the tracks
print_tracks(tracks)
end
Upvotes: 2
Reputation: 96
First of all you are calling print_tracks(tracks)
twice in main()
method
Upvotes: 5