I have this code running fine but then it shows too much information and I only want the last line in the code.
Code here:
import scala.io.Source
object CovidWorld {
def main(args: Array[String]): Unit = {
val filename = Source.fromFile("OOPAssignment3.txt")
try{
for (line <- filename.getLines.toList) {
if (line.contains("Malaysia") && line.split(",").apply(7).nonEmpty) {
val allDeathString: String = line.split(",").apply(7)
print("\n\n Malaysia latest total amount of death: " allDeathString)
}
}
}
finally{
filename.close
//print("\nThe file is now closed")
}
}
}
This is the result I obtain from it.result of the running code
I just want the last line of the information instead of the entire thing. Anyone can figure out how? Thanks in advance for the help :)
CodePudding user response:
You can replace the inside of your try
block with:
filename
.getLines
.filter(line => line.contains("Malaysia") && line.split(",").apply(7).nonEmpty)
.toList
.takeRight(1)
.foreach(line => {
val allDeathString: String = line.split(",").apply(7)
print("\n\n Malaysia latest total amount of death: " allDeathString)
})
The key part for your purposes is takeRight
which selects n
elements from the end of the list. When n == 1
you're taking only the last match which is what you want here.