Decreasing for loop in Scala?

前端 未结 8 1003
一生所求
一生所求 2020-12-17 20:24

First day and first attempt at using Scala - so go easy on me! I\'m trying to rewrite some old Java code I have which is simply a function which takes two numbers and prints

8条回答
  •  死守一世寂寞
    2020-12-17 21:05

    def printInDecreasingOrder(start : Int, end : Int){
      if(start > end ){
         for(i <- start to end by -1){
           println(s"Current value (decreasing from $start to $end) is $i")
         }
       }else{
         println("first num is smaller than second")
       }
    }
    

    method call:

    printInDecreasingOrder(10, 2)

    Result:

    Current value (decreasing from 10 to 2) is 10

    Current value (decreasing from 10 to 2) is 9

    Current value (decreasing from 10 to 2) is 8

    Current value (decreasing from 10 to 2) is 7

    Current value (decreasing from 10 to 2) is 6

    Current value (decreasing from 10 to 2) is 5

    Current value (decreasing from 10 to 2) is 4

    Current value (decreasing from 10 to 2) is 3

    Current value (decreasing from 10 to 2) is 2

    printInDecreasingOrder(1, 10)

    Result:

    first num is smaller than second

提交回复
热议问题