페이지

2015년 11월 2일 월요일

Scala2e Chapter3 Next Steps in Scala - Step 12. Read lines from a file

In this section, you'll build a script that reads lines from a file and prints them out prepended with the number of characters in each line.

import scala.io.Source
if(argslength > 0){
   for(line <- args="" getlines="" p="" source.fromfile="">       println(line.length + "  "  + line)
   }
}else
   Console.err.println("Please enter filename")

To accomplish this, you can iterate through the lines twice. The first time through you'll determine the maximum width required by any line's character count. the second time through you'll print the output, using the maximum width calculated previously. Because you'll be iterating through the lines twice, you may as well assign them to a variable:

val lines = Source.fromFile(args(0)).getLines().toList

The lines variable, therefore, references a list of strings that contains the contents of the file specified on the command line.

def widthOfLength(s: String) = s.length.toString.length

with the function, you could calculate the maximum width liek this:

var maxWidth = 0
for(line <- lines="" p="">   maxWidth = maxWidth.max(widthOfLength(line))

import scala.io.Source

def widthOfLength(s:String) = s.length.toString.length

if(args.length > 0 ){
   val lines = Source.fromFile(args(0)).getLines().toList

   val longestLine = lines.reduceLeft(
       (a, b) => if(a.length > b.length ) a else b
   )
   val maxWidth = widthOfLength(longestLine)


   for(line <- lines="" p="">      val numSpaces = maxWidth - widthOfLength(line)
      val padding = " " * numSpaces
      println(padding + line.length + " | " + line)
   }
}
else
     Console.err.println("Please enter filename")








댓글 없음: