1. 程式人生 > >《快學Scala》第九章習題解答

《快學Scala》第九章習題解答

RT。

package com.scalalearn.scala.main

import java.io._

import scala.math._
import scala.collection.mutable.ArrayBuffer
import scala.io.{BufferedSource, Source}

/**
  * 快學scala 09習題
  */
class Person extends Serializable{
  var friends:ArrayBuffer[Person] = new ArrayBuffer[Person]()
  var name:String = ""

  def this(name:String){
    this()
    this.name = name
  }

  def getName():String={
    this.name
  }

  def addFriend(person:Person): Unit ={
    friends += person
  }

  def getFriendList():Unit = {
    for(person <- friends){
      print(person.getName()+" ")
    }
    println
  }
}

object LearnScala09 {
  //1.編寫一段scala程式碼,將某個檔案的行逆序
  def execise1(srcFile:String,dstFile:String):Unit = {
    var source:BufferedSource = null
    try{
      source = Source.fromFile(srcFile)
      var lines = source.mkString.split("\r\n").reverse
      var out = new PrintWriter(dstFile)
      for(line<-lines) out.println(line)
      if(out != null) out.close()
    }catch{
      case _:Exception=>println("error")
    }finally{
      if(source != null) source.close()
    }
  }

  //2.編寫一個scala程式,從一個帶有製表符的檔案讀取內容,將每個製表符都替換成空格,使得製表符隔開的n列仍保持對齊
  def execise2(srcFile:String):Unit = {
    var source:BufferedSource = null

    try{
      var lines = Source.fromFile(srcFile).mkString
      lines = lines.replaceAll("\t"," "*4)

      var out = new PrintWriter(srcFile)
      out.print(lines)
      out.close()
    }catch{
      case _:Exception=>println("error")
    }finally{
      if(source != null) source.close()
    }
  }

  //3.編寫一小段程式,將字元數>12的單詞列印到控制檯;如果用單行完成,將有額外獎勵
  def execise3(srcFile:String):Unit = {
    for(line<-Source.fromFile(srcFile).mkString.replaceAll("\r\n"," ").split(" ") if line.length > 12) println(line)
  }

  //4.編寫scala程式,從含有浮點數的檔案中讀取內容,計算浮點數之和,平均值,最大值和最小值
  def execise4(srcFile:String):Unit = {
    var arr:ArrayBuffer[Float] = new ArrayBuffer[Float]()
    for(line:String<-Source.fromFile(srcFile).mkString.replaceAll("\r\n"," ").split(" ")){
      arr += line.toFloat
    }

    println("total:"+arr.sum)
    println("avg:"+arr.sum/arr.toList.size)
    println("min:"+arr.min)
    println("max:"+arr.max)
  }

  //5.編寫scala程式,向檔案中寫入2的n次方及其倒數,指數n從0到20
  def execise5(dstFile:String):Unit = {
    var out = new PrintWriter(dstFile)
    var line = ""
    for(i <- 0 to 20){
      line += pow(2,i)+"\t"+1/pow(2,i)+"\r\n"
    }
    out.println(line)
    out.flush()
    out.close()
  }

  //6.編寫正則表示式,匹配Java或C++中帶引號的字串,並將它打印出來
  def execise6(srcFile:String):Unit = {
    var source:BufferedSource = null

    try{
      var lines = Source.fromFile(srcFile).mkString.split("\r\n")
      val pattern = """["']""".r
      for(line <- lines){
        if(pattern.findFirstIn(line) != None){
          println(line)
        }
      }
    }catch{
      case _:Exception=>println("error")
    }finally{
      if(source != null) source.close()
    }
  }

  //7.讀取檔案,將非浮點數打印出來,用正則表示式實現
  def execise7(srcFile:String):Unit = {
    var source:BufferedSource = null

    try{
      var lines = Source.fromFile(srcFile).mkString.replaceAll("\r\n"," ").split(" ")
      val pattern = """\d.\d""".r
      for(line <- lines){
        if(pattern.findFirstIn(line) != None){
          println(line)
        }
      }
    }catch{
      case _:Exception=>println("error")
    }finally{
      if(source != null) source.close()
    }
  }

  //8.編寫scala程式,列印某個html頁面中的所有img標籤的src屬性
  //用正則分組
  def execise8(url:String):Unit = {
    var source:BufferedSource = null

    try{
      var htmlContent = Source.fromURL(url,"utf-8").mkString
      //println(htmlContent)
      var pattern = """<img.*?>""".r
      val srcpattern = """src=("[^"]+")|('[^']+')""".r
      var arr = pattern.findAllIn(htmlContent).toArray
      for(line <- arr){
        println("url:"+line.toString)
        if(srcpattern.findFirstIn(line) != None){
          println(srcpattern.findFirstIn(line).getOrElse())
        }
      }
    }catch{
      case ex:Exception=>println(ex)
    }finally{
      if(source != null) source.close()
    }
  }

  //9.編寫scala檔案,判斷給定目錄下有多少個以.class結尾的檔案
  def execise9(dir:File):Unit = {
    var count:Int = 0
    println(dir.listFiles().filter(_.isFile).filter(_.toString.endsWith(".class")).size)
  }

  //10.擴充套件Person類,並將其序列化;最後再讀取
  def execise10():Unit = {
    var person1 = new Person("關羽")
    var person2 = new Person("劉備")
    var person3 = new Person("張飛")
    person2.addFriend(person1)
    person2.addFriend(person3)
    var arrs = Array(person1,person2,person3)

    var out = new ObjectOutputStream(new FileOutputStream("d:/personobj"))
    out.writeObject(arrs)
    out.flush()
    out.close()

    var in = new ObjectInputStream(new FileInputStream("d:/personobj"))
    var readObj:Array[Person] = in.readObject().asInstanceOf[Array[Person]]
    println(readObj(1).getName())
    readObj(1).getFriendList()
  }

  def main(args:Array[String]):Unit = {
    println("====================execise1=====================")
    //LearnScala09.execise1("d:/test1.txt","d:/test2.txt")

    println("====================execise2=====================")
    //LearnScala09.execise2("d:/test3.txt")

    println("====================execise3=====================")
    //LearnScala09.execise3("d:/test4.txt")

    println("====================execise4=====================")
    //LearnScala09.execise4("d:/test5.txt")

    println("====================execise5=====================")
    //LearnScala09.execise5("d:/test6.txt")

    println("====================execise6=====================")
    //LearnScala09.execise6("d:/test6.scala")

    println("====================execise7=====================")
    //LearnScala09.execise7("d:/test7.txt")

    println("====================execise8=====================")
    //LearnScala09.execise8("http://news.sina.com.cn/2016-05-17/doc-ifxsenvm0533979.shtml")

    println("====================execise9=====================")
    //LearnScala09.execise9(new File("d:"))

    println("====================execise10=====================")
    LearnScala09.execise10
  }
}