Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Scala Console | println, printf and readLine

In Scala, just like in many other programming languages, there are standard methods to output to the console and read input from it. Here's a breakdown of println, printf, and readLine which are among the most commonly used methods for console operations in Scala:

  1. println:

    • Used to print a line to the console.
    • It automatically appends a newline character at the end.
    • It can take any type as an argument because any object can be implicitly converted to a string in Scala.
    println("Hello, World!")
    val name = "Alice"
    println(s"Hello, $name!")
    
  2. printf:

    • Used for formatted output.
    • Similar to C's printf or Java's System.out.printf.
    • Uses format specifiers.
    val name = "Alice"
    val age = 30
    printf("Name: %s, Age: %d\n", name, age)
    

    Some common format specifiers:

    • %s - String
    • %d - Decimal (base-10 integer)
    • %f - Floating-point number
    • %n - Newline (Platform-specific newline character(s))
  3. readLine:

    • Used to read a line of input from the console until the Enter key is pressed.
    • Can be provided with an optional prompt string.
    val input = readLine("Enter your name: ")
    println(s"Hello, $input!")
    

    Note: readLine is part of scala.io.StdIn. Depending on the context, you might need to import it explicitly:

    import scala.io.StdIn.readLine
    

When working with the console, these methods provide simple ways to interact with the user. println and printf are used for output, while readLine is used for input. It's worth noting, though, that for more complex applications (e.g., those with graphical interfaces or web interfaces), you would typically move beyond these basic console methods.

  1. Using println for Console Output in Scala:

    The simplest way to output information to the console is using println.

    val message = "Hello, Scala!"
    println(message)
    
  2. Formatting Output with printf in Scala:

    The printf method allows you to format console output.

    val name = "John"
    val age = 25
    printf("Name: %s, Age: %d\n", name, age)
    
  3. Read User Input with readLine in Scala:

    You can read user input from the console using the readLine method.

    print("Enter your name: ")
    val userName = scala.io.StdIn.readLine()
    println(s"Hello, $userName!")
    
  4. Interactive Console Applications in Scala:

    Combine input and output for interactive console applications.

    print("Enter your age: ")
    val age = scala.io.StdIn.readInt()
    println(s"Next year, you'll be ${age + 1} years old.")
    
  5. Handling User Input Validation in Scala:

    Validate user input to ensure it meets specific criteria.

    var validInput = false
    var userInput: Int = 0
    
    while (!validInput) {
      print("Enter a positive number: ")
      userInput = scala.io.StdIn.readInt()
      validInput = userInput > 0
      if (!validInput) println("Invalid input. Please enter a positive number.")
    }
    
    println(s"You entered: $userInput")
    
  6. Formatted String Interpolation in Scala:

    Use string interpolation for cleaner and more readable code.

    val product = "Scala Book"
    val price = 29.99
    println(f"Product: $product, Price: $$$price%.2f")
    
  7. Advanced Formatting Options with printf in Scala:

    Explore advanced formatting options with printf.

    val pi = math.Pi
    printf("Value of pi: %.4f\n", pi)
    
  8. Building Interactive Menus with Scala Console Input and Output:

    Create interactive menus for user-friendly console applications.

    def displayMenu(): Unit = {
      println("1. Option 1")
      println("2. Option 2")
      println("3. Exit")
    }
    
    var choice = 0
    while (choice != 3) {
      displayMenu()
      print("Enter your choice: ")
      choice = scala.io.StdIn.readInt()
    
      choice match {
        case 1 => println("You chose Option 1.")
        case 2 => println("You chose Option 2.")
        case 3 => println("Exiting...")
        case _ => println("Invalid choice. Please try again.")
      }
    }