Tavern Data - Extra Blank Line?

I was wondering if anyone is getting an extra blank line when reading the tavern data. I’m reading the data as outlined in the book:

val menuList = File("data/tavern-menu-data.txt")
            .readText()
            .split("\n")

However, I seem to be getting one additional, blank element when printing the contents of menuList. When the following code is ran…

    menuList.forEachIndexed { index, entry ->
    println("$index : $entry")
}

…I get the following output:

0 : shandy,Dragon’s Breath,5.91
1 : elixir,shirley temple,4.12
2 : meal,goblet of la croix,1.22
3 : desert dessert,pickled camel hump,7.33
4 : elixir,iced boilermaker,11.22
5 :

Would anyone happen to know why I’m getting the extra last element? I’ve checked the file and made sure that there is no blank line at the end of the file. Any insight on this is appreciated :slight_smile:

I was able to figure out this issue. I first started out by figuring out where the new line characters were appearing within the file. I opened the tavern data within Vim and used :set list for the new line characters to be shown as $ at the end of each line:

Capture

That lines up with why I’m getting an empty 6th entry in my array: there’s a newline character at the end of the 5th line and, for whatever reason, split adds a new element empty entry to menuList due to this. To get around this issue, I used readLines() instead:

val menuList = File("data/tavern-menu-data.txt")
            .readLines()

No extra entry. Everything appears to be working just fine now. Hopefully this helps someone else down the line.

2 Likes

I ran into the same issue. By default, Unix/Linux text editors end every non-empty file with a newline character, but that can be changed. I use Gedit on the Gnome desktop where entering the following into a shell will accomplish that result:

gsettings set org.gnome.gedit.preferences.editor ensure-trailing-newline false

I imagine other text editors allow equivalent tweaks to settings.