scala 方法调用
Calling a method in Scala: simply call the function using a method call in Scala, but, calling method N times can be done using either of the two ways:
在Scala中调用方法 :只需在Scala中使用方法调用来调用函数,但是,可以使用以下两种方法之一来调用方法N次 :
Using iteration
使用迭代
Using recursion
使用递归
1)使用迭代调用方法N次 (1) Calling method N times using iteration)
A simple logic to call a method n times is using on a loop that runs n times. And at each iteration, the loop calls the method. So, the same method is called n times.
n次调用方法的简单逻辑是在运行n次的循环中使用。 并且在每次迭代时,循环都会调用该方法。 因此,相同的方法称为n次。
Example:
例:
Calling a method 5 times that prints "I love includeHelp" using a loop:
调用一个方法5次,并使用循环显示“ I love includeHelp”:
object MyClass {
def printStatement(){
println("I love includeHelp");
}
def main(args: Array[String]) {
val n = 5;
for(i <- 1 to n){
printStatement();
}
}
}
Output
输出量
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
2)使用递归调用方法N次 (2) Calling method N times using recursion)
Another logic to call a method n times is using recursion, with parameter as the remaining numbers of time the function is to be run. At each call, the number value passed is decreased by one and the function's recursive call ends when 1 is encounters at n.
调用方法n次的另一种逻辑是使用递归,其中参数作为函数要运行的剩余时间。 在每个调用中,传递的数值减少1,并且在n处遇到1时,函数的递归调用结束。
Example:
例:
Calling a method 5 times that prints "I love includeHelp" using a recursion :
使用递归调用5次打印“ I love includeHelp”的方法:
object MyClass {
def printStatement( n: Int){
println("I love includeHelp");
if(n!= 1 ){
printStatement(n-1);
}
}
def main(args: Array[String]) {
val n = 5;
printStatement(n);
}
}
Output
输出量
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
翻译自: https://www.includehelp.com/scala/how-to-call-method-n-times-in-scala.aspx
scala 方法调用