Decreasing for loop in Scala?

前端 未结 8 931
一生所求
一生所求 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:26
    object Test extends App{
    
      def decrement(start: Int, finish: Int,dec :Int) = {
        for (i <- Range(start,finish,dec)) {
          println("Current value (decreasing from "+start+" to "+finish+") is "+i)
        }
      }
    
      decrement(5,0,-1)
    }
    

    This is also a method. but may not be the best

    0 讨论(0)
  • 2020-12-17 21:29
    scala>def decrement(start: Int, finish: Int) = {
        |  for (i <- start to finish by -1)
        |   println("Current value (decreasing from "+start+" to "+finish+") is "+i);
        | }
    decrement: (start: Int,finish: Int)Unit
    
    scala> decrement(10, 1)
    Current value (decreasing from 10 to 1) is 10
    Current value (decreasing from 10 to 1) is 9
    Current value (decreasing from 10 to 1) is 8
    Current value (decreasing from 10 to 1) is 7
    Current value (decreasing from 10 to 1) is 6
    Current value (decreasing from 10 to 1) is 5
    Current value (decreasing from 10 to 1) is 4
    Current value (decreasing from 10 to 1) is 3
    Current value (decreasing from 10 to 1) is 2
    Current value (decreasing from 10 to 1) is 1
    
    0 讨论(0)
提交回复
热议问题