[Scala] How do I handle user input in Scala?

There are several ways to handle user input in Scala. Here are a few common approaches:

  1. Using the scala.io.StdIn object: Scala provides the scala.io.StdIn object, which allows you to read input from the console. You can use the readLine method to read a line of input as a string, and then parse it as needed. For example:
1val input = scala.io.StdIn.readLine("Enter your name: ")
2println(s"Hello, $input!")
  1. Using the java.util.Scanner class: Scala also allows you to use the java.util.Scanner class, which provides more advanced input parsing capabilities. You can create an instance of Scanner and use its various methods to read input. For example:
1import java.util.Scanner
3val scanner = new Scanner(System.in)
4println("Enter your age: ")
5val age = scanner.nextInt()
6println(s"You are $age years old.")
7scanner.close()  // Remember to close the scanner when you're done using it.
  1. Using command-line arguments: If you want to pass input to a Scala program from the command line, you can access the command-line arguments through the args array in the main method. For example:
1object MyProgram {
2  def main(args: Array[String]): Unit = {
3    val name = args(0)
4    val age = args(1).toInt
5    println(s"Hello, $name! You are $age years old.")
6  }

You can run this program with command-line arguments like: scala MyProgram John 25.

These are just a few examples of how you can handle user input in Scala. The most appropriate approach depends on your specific requirements and use case.