object Scala_List {
def Nth_num[A](nums: List[A], n: Int ): A = {
if (n < 0) throw new IllegalArgumentException("Nth position is less than 1!")
if (n > nums.length) throw new NoSuchElementException("Nth position greater than list length!")
nums(n)
}
def main(args: Array[String]): Unit = {
val nums = List(10, 20, 30, 40, 50, 70, 90, 110, 140, 120, 160)
println("Original list:")
println(nums)
println("3rd element of the said element: " + Nth_num(nums, 2));
println("6th element of the said element: " + Nth_num(nums, 5));
println("1st element of the said element: " + Nth_num(nums, 0));
}
}
Sample Output:
Original list:
List(10, 20, 30, 40, 50, 70, 90, 110, 140, 120, 160)
3rd element of the said element: 30
6th element of the said element: 70
1st element of the said element: 10
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer