import scala.io.Source
def widthOfLines(s:String):Int=s.length.toString.length
val f = Source.fromFile("main.scala")
val linesList=f.getLines().toList
val maxLine=linesList.reduceLeft((a:String,b:String)=>
if (a.length>b.length)a
else b)
val padding=widthOfLines(maxLine) //padding:Int 43 -> 2
for (m<-linesList){
val lenM=widthOfLines(m)
println(m.length+" "*(padding-lenM)+"| "+m)
}
import java.io.{PrintWriter, File}
import scala.io.Source
def searchItemFrom(x:Int,c:Char,s:String):AnyVal= //查找字符里的char
if (x>=s.length)-1
else if (s(x)!=c) searchItemFrom(x+1,c,s)
else x
def factoria(x:Int):Int={//求阶乘
def factoriaInner(a:Int,b:Int):Int={
if(a<=1&&b<=1)1
else if(a==1)b
else factoriaInner(a-1,b*(a-1))
}
factoriaInner(x,x)
}
def makeRowSeq(row:Int)={//打印乘法表
for(col<-1 to 10)yield {
val prod=(row*col).toString
val padding=" "*(4-prod.length)
padding+prod
}
}
def makeRow(x:Int)=makeRowSeq(x).mkString
def makeTable()={
val lists=for(row<-1 to 10)yield {
makeRow(row)
}
lists.mkString("\n")
}
def processFile(fileName:String,width:Int)={
def processLine(line:String)={
if(line.length>width)println(line)
}
val f = new File(fileName)
val linesList =Source.fromFile(f).getLines().toList
for(line<-linesList)yield{processLine(line)}
}
object filesFinding{
val filesHere = (new File(".")).listFiles()
def filesMatch(query:String,matching:(String,String)=>Boolean)={
for(f <- filesHere if(matching(f.getName,query)))yield f.getName
}
}
def containsNeg(l:List[Int]):Boolean=l.exists(_<0)//判断是否有负数
def containsOdd(l:List[Int]):Boolean=l.exists(_%2==1)
val a=List(1,2,3,4)
def withPrintWriter(file:File,op:PrintWriter=>Unit): Unit ={
val writer = new PrintWriter(file)
try{
op(writer)
} finally {
writer.close()
}
}
class A{
val a=10
}
class B{
val b=20
}
def process(a:A,op:B=>Unit)={
val n=new B
try op(n)
finally println(a.a)
}
process(new A,b=>println(b.b))