函数参数的使用
object inout42 {
def hello(name:String="小明",age:Int=17,gender:String="女"):Unit = {
println(s"hello, 我是${name},${age}岁,性别:${gender}")
}
def main(args:Array[String]):Unit = {
hello("小花",18,"女")
hello("小明",19,"男")
hello("小花",18)
hello()
}
}
object inout42 {
def hello(name:String="小明",age:Int=17,gender:String="女"):Unit = {
println(s"hello, 我是${name},${age}岁,性别:${gender}")
}
def main(args:Array[String]):Unit = {
hello("小花",18,"女")
hello("小明",19,"男")
hello("小花",18)
hello()
hello(age=18)
hello(gender="男",name="小李")
hello(gender="男",name="小李")
}
}
定义函数的时候,不写(),那么在调用函数的时候,也不能写()
def test:Unit = {
println("test......")
}
def main(args:Array[String]}:Unit = {
test
test()
允许参数的个数不同,类型相同
object inout43 {
def getSum(args:Int*):Int = {
var sum = 0
for(i <- args){
sum += i
}
sum
}
def main(args: Array[String]): Unit = {
val result1 = getSum(1)
val result2 = getSum(4,1,2,3,5)
println(result1,result2)
}
}
判断给定的三角形的三边,能否构成一个三角形?
object inout44 {
def testTringle(a: Double, b: Double, c: Double): Boolean = {
a + b > c && a + c > b && b + c > a
}
def isPrime(num: Int): Boolean = {
var isPrimeNum = true
for (i <- 2 to num - 1) {
if (num % i == 0) {
isPrimeNum = false
}
}
isPrimeNum
}
def main(args: Array[String]): Unit = {
val r = testTringle(1.0, 2.0, 2.0)
println(r)
var r1 = isPrime(9)
println(r1)
}
}