今天完成了spark实验四的编程。起初是在eclipse上安装了Scala的环境,同通过环境进行的相关内容的编程,Scala的编程和Java编程的思路差不多,在编程时的相关语句以及用法不太一样所以耗费了一些时间。程序代码。
源代码:
import scala.io.Source
import java.io.PrintWriter
import java.io.File
import Array._
import scala.util.control._
object exercise4_2 {
def main(args: Array[String]){
File()
}
def File(){
val AFile=InFile("A.txt")
val BFile=InFile("B.txt")
var CFile=concat( AFile, BFile)
var CFile2=new Array[String](CFile.size)
val loop = new Breaks;
for(i<-CFile){
loop.breakable{
for(j<- 0 to CFile2.size-1 ){
if(CFile2(j)!=null){if(i==CFile2(j))loop.break;}
else {CFile2(j)=i;loop.break;}
}
}
}
outFile(CFile2)
}
def InFile(path:String) : Array[String] ={
val source = Source.fromFile(path, "UTF-8")
val lines = source.getLines().toArray
return lines
}
def outFile(data:Array[String]){
val writer = new PrintWriter(new File("C.txt"))
for(i <-data)
if(i!=null)writer.println(i)
writer.close()
}
}
求平均值
import scala.io.Source import java.io.PrintWriter import java.io.File import Array._ import scala.util.control._ object exercise4_3 { def main(args: Array[String]){ File() } def File(){ val data=InFile("student.txt") var student= ofDim[String](4,2) val loop = new Breaks; var time:Int=0 for(i<-data){ var text=String.valueOf(i); var text2=text.split(" ") loop.breakable{ for(j<- 0 to student.size-1){ if(student(j)(0)==null){student(j)(0)=text2(0);student(j)(1)=text2(1);loop.break;} else{ if(text2(0)==student(j)(0)){student(j)(1)=String.valueOf(student(j)(1).toInt+text2(1).toInt);time+=1} } }} } for(j<-0 to 3){ student(j)(1)=String.valueOf(student(j)(1).toDouble/3) } outFile(student) } def InFile(path:String) : Array[String] ={ val source = Source.fromFile(path, "UTF-8") val lines = source.getLines().toArray return lines } def outFile(data:Array[Array[String]]){ val writer = new PrintWriter(new File("avg.txt")) for(i <-0 to data.size-1) writer.println(data(i)(0)+" "+data(i)(1)) writer.close() } }