w3resource

Scala Program: Check Palindrome using if/else and pattern matching


Write a Scala program to check if a given string is a palindrome using if/else statements and pattern matching.


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • String Manipulation: Knowledge of working with strings, including reversing and comparing them.
  • If/Else Statements: Understanding how to use if/else statements to handle conditions.
  • Pattern Matching: Awareness of using pattern matching for comparisons and decision-making.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Main Object: Create an object with a main method, which serves as the entry point of the program.
  • Initialize the String: Declare a variable to store the string you want to check for palindrome properties.
  • Check Using If/Else: Write a function that reverses the string and uses an if/else statement to compare the reversed string with the original. Return true if they match, otherwise false.
  • Check Using Pattern Matching: Write another function that uses pattern matching to compare the reversed string with the original. Return true if they match, otherwise false.
  • Display the Result: Use println() to print whether the string is a palindrome or not, based on the result from either function.
  • Test with Different Strings: Change the input string to verify the program works for various cases, including palindromes, non-palindromes, empty strings, and strings with special characters.
  • Common Errors to Avoid:
    • Forgetting to reverse the string correctly, leading to incorrect results.
    • Misplacing the comparison logic in if/else or pattern matching, causing incorrect palindrome detection.
    • Not handling edge cases like empty strings or strings with spaces, which may require additional preprocessing.

Sample Solution:

Scala Code:

object PalindromeChecker {
  def main(args: Array[String]): Unit = {
        val str: String = "madam" // String you want to check
    //  val str: String = "Scala" // String you want to check

    // Check using if/else statements
    val isPalindrome: Boolean = checkPalindromeIfElse(str)
    if (isPalindrome) {
      println(s"The string $str is a palindrome.")
    } else {
      println(s"The string $str is not a palindrome.")
    }

  }

  def checkPalindromeIfElse(str: String): Boolean = {
    val reversed = str.reverse
    if (str == reversed) {
      true
    } else {
      false
    }
  }

  def checkPalindromeMatch(str: String): Boolean = {
    str.reverse match {
      case `str` => true
      case _     => false
    }
  }
}

Sample Output:

The string madam is a palindrome.
The string Scala is not a palindrome.

Explanation:

In the above exercise -

  • First we define a variable str and assign it a value ("level" in this case) representing the string we want to check for palindromes.
  • We have two functions: "checkPalindromeIfElse()" and "checkPalindromeMatch()". The first function uses if/else statements to check if the given string is a palindrome. It reverses the string using the reverse method and compares it with the original string. If they are equal, it returns true; otherwise, it returns false.
  • The second function, "checkPalindromeMatch()", uses pattern matching. It reverses the string and matches it against the original string using a pattern. If the reversed string matches the original string, it returns true; otherwise, it returns false.
  • We call both functions and print the results using println. If the returned value is true, the string is a palindrome; otherwise, it is not a palindrome.

Scala Code Editor :

Previous: Scala program to find the sum of array elements using a for loop.
Next: Count vowels with if/else and pattern matching.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.