Open In App

How to take Input from a User in Scala?

Last Updated : 08 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This article focuses on discussing various approaches to taking input from a user in Scala.

Using scala.io.StdIn.readLine() Method

Below is the Scala program to take input from the user:

Scala
object UserInputExample {
  def main(args: Array[String]): Unit = {
    println("Enter your name:")
    val name = scala.io.StdIn.readLine()    
    println("Hello, " + name + " Welcome!")
  }
}

Output:

scala.io.StdIn.readLine() Output
scala.io.StdIn.readLine() Output

Using java.util.Scanner

Below is the Scala program to take an input from user:

Scala
import java.util.Scanner

object UserInputExample {
  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    println("Enter your name:")
    val name = scanner.nextLine()
    println("Hello, " + name + " Welcome!")
  }
}

Output:

java.util.Scanner Output
java.util.Scanner Output

Explanation:

In this example, we import java.util.Scanner and use it to read input from the standard input stream using nextLine() method.

Using Command-line Argument

Below is the Scala program to take an input from user:

Scala
object UserInputExample {
  def main(args: Array[String]): Unit = {
    if (args.length > 0) {
      val name = args(0)
      println("Hello, " + name + " Welcome!")
    } else {
      println("Please provide your name as a command-line argument.")
    }
  }
}

Output:

Command-line Argument
Command-line Argument Output

Next Article
Article Tags :

Similar Reads