你想了解大数据,你想成为年薪百万吗?那你还等着什么,快点来吧!跟着王家林老师学习spark大数据
第二讲主要讲了Scala函数定义、流程控制、异常处理入门
函数定义:
关键字(def) 函数名称 参数(参数名称:参数类型):返回内容类型 = {
函数体
}
注意:
Unit:空的返回内容
Scala结束语是不需要写分号
下面一代码为例:
//不带参数
Object ScalaBasics{
def doWhile(){
var line = “”
do{
line = readLine()
printIn(“Read: ”+ line)
}while (line != “”)
}
def main (args: Array [String]){
dowhile
}
//注意:dowhile后面的()可加可不加,没有参数就不写
//带参数
def looper (x : Long, y : long) : Long = {
var a = x
var b =y
while(a != 0){
val temp = a
a = b % a
b = temp
}
b
}
def main (args: Array [String]){
printIn(looper(100,298))
}
流程控制
def main (args: Array [String]){
var file = “scala.txt”
if ( !args.isEmpty) file = args(0)
}
printIn(file)
var file = if ( !args.isEmpty) args(0) else file = “scala.xml”
printIn(if ( !args.isEmpty) args(0) else file = “scala.xml”)
for (I <- 1 to 10) {
printIn(“Number is :” +i)
}
//1to10另外一种写法
for (I <- 1.to (10))
val files = (new java.io.file(“.”)) listFiles()
for (file <- files){
printIn(file)
}
object ScalaBasics{
var line = “”
do{
printIn (“Please input some words blow…..”)
line = readLine()
printIn(“Read: ” + line)
}while (line != “”)
}
异常处理
Val n =99
//val file = “Spark.txt”
//openFile(file)
try{
val half = if (n % 2 ==0) n / 2 else throw
new RuntimeException(“N must be event”)
// Use the file
}catch {
Case e : Exception => printIn(“The exception is :” + e.getMessage())
}finally{
//close(file)
}
通过简单代码示例,从基础了解Scala的特性和对函数定义、流程控制、异常处理基本了解和掌握,希望自己跟着老师学习一点一点进步;
如果你了解的还是不清楚,你也可以学习此视频或者是记录一下联系方式
视频地址:http://www.tudou.com/programs/view/eN90M1SI8E8/
学习地址:http://mp.weixin.qq.com/s?__biz=MzAwNjAwODI3Mg==&mid=212579488&idx=2&sn=883193df2b3df163d49c4fdec1ecd585&scene=5#rd