w3resource

Scala Programming: Find the larger value from two positive integer values that is in the range 20..30 inclusive

Scala Programming Basic Exercise-22 with Solution

Write a Scala program to find the larger value from two positive integer values in the range 20..30 inclusive, or return 0 if neither is in that range.

Sample Solution:

Scala Code:

object scala_basic {
  def test(x: Int, y: Int): Int = {
    val max_of_two = List(x, y).max
    if (max_of_two >= 20 && max_of_two <= 30) max_of_two else 0
    }     
   def main(args: Array[String]): Unit = {
      println("Result: " + test(78,95));
      println("Result: " + test(20,30));
      println("Result: " + test(21,25));      
      println("Result: " + test(28,28));      
    }
  }

Sample Output:

Result: 0
Result: 30
Result: 25
Result: 28

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to check whether two given integers are in the range 40..50 inclusive, or they are both in the range 50..60 inclusive.
Next: Write a Scala program to check whether a given character presents in a string between 2 to 4 times.

What is the difficulty level of this exercise?