当前位置: 代码迷 >> 其他开发语言 >> Scala教程上画图的例子如何运行结果不对
  详细解决方案

Scala教程上画图的例子如何运行结果不对

热度:240   发布时间:2016-05-02 04:03:15.0
Scala教程上画图的例子怎么运行结果不对?
import DrawGraphic.coin
abstract class DrawGraphic {
  val contents:  Array[String]
  def higth: Int = contents.length
  def width: Int = if(higth == 0) 0 else contents(0).length
//左右连接的方法
  def connect(that: DrawGraphic): DrawGraphic = 
  {
    val this1 = this.comparehigth(that.higth)
    val that1 = that.comparehigth(higth)
    coin(this1.contents ++ that1.contents)
  }
//上下连接的方法
  def splice(that: DrawGraphic): DrawGraphic = 
  {
    val this1 = this.comparewidth(that.width)
    val that1 = that.comparewidth(width)
    coin(
    for((line1,line2) <- this1.contents zip that1.contents)
      yield line1 + line2)
  }
  override def toString = contents.mkString("\n" )
//比较宽度的辅助方法
  def comparewidth(n: Int): DrawGraphic = 
  {
    if(n <= width)
      this
    else
    {
      val left = coin('-',(n-width)/2,higth)
      val right = coin('-',n-width-left.width,higth)
      left connect this connect right
     }
  }
//比较高度的辅助方法
  def comparehigth(h: Int): DrawGraphic = 
  {
    if(h <= higth)
      this
    else
    {
      val top = coin('+',width,(h-higth)/2)
      val bot = coin('+',width,h-higth-top.higth)
      top splice this splice bot
     }
  } 
}
//伴生对象及工厂方法
object DrawGraphic {  
  class ArrayDraw(val contents: Array[String]) extends DrawGraphic
  private class LineDraw(line: String) extends DrawGraphic {
    val contents = Array(line)
    override val width = line.length
    override val higth = 1
  }
  private class Graphic(ch: Char,width: Int,higth: Int) extends DrawGraphic {
    private val lines = ch.toString * width
    val contents = Array.fill(higth)(lines)
  }
  def coin(contents: Array[String]): DrawGraphic = new ArrayDraw(contents)
  def coin(line: String): DrawGraphic = new LineDraw(line)
  def coin(ch: Char,width: Int,higth: Int): DrawGraphic = new Graphi(ch,width,higth)
}
以上代码就是书上的例子,写完后,自己new了一个实例运行进行测试,发现结果跟预期不一样,求Scala高手指点:println(new ArrayDraw(Array("Mouse")) connect new ArrayDraw(Array("Cat")))
Scala ?编程

------解决方案--------------------
Scala代码写的和java一样,:-(
  相关解决方案