一个空的块表达式{}的值是什么?类型是什么? 值是()类型是Unit针对下列Java循环编写一个Scala版本: for(int i=10;i>=0;i–)System.out.println(i);
for(i<- Range(10,-1,-1)){
println(i)
}
for (i<-0 to 10 reverse){
println(i)
}
编写一个过程countdown(n:Int),打印从n到0的数字
def countDown(n:Int){
if(n<0) return
println(n)
countDown(n-1)
}
def countDown2(n:Int):Unit={
(0 to n).reverse.foreach(println)
}
编写一个for循环,计算字符串中所有字母的Unicode代码(toLong方法)的乘积。举例来说,"Hello"中所有字符串的乘积为9415087488L
var dul = 1L
for(i<-0 until str.length){
dul *= str.charAt(i).toLong
}
或者
for(i<-"Hello"){
dul *= i.toLong
}
同样是解决前一个练习的问题,请用StringOps的foreach方式解决。
def stringUnicode2(str:String):Long={
var dul = 1L
str.foreach(ch=>dul*=ch.toLong)
dul
}
var dul = 1L
str.foreach(dul *= _.toLong)
dul
编写一个函数product(s:String),计算字符串中所有字母的Unicode代码(toLong方法)的乘积把7练习中的函数改成递归函数
def product(s:String,i:Int):Long={
if (i==s.length-1)
s.charAt(i).toLong
else
s.charAt(i).toLong*product(s,i+1)
}
def product1(s:String):Long={
if (s.length == 1)
s.charAt(0).toLong
else
s.take(1).charAt(0).toLong * product1(s.drop(1))
}
转载请注明原文地址:https://blackberry.8miu.com/read-29207.html