How to resolve the algorithm Menu step by step in the Scala programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Menu step by step in the Scala programming language

Table of Contents

Problem Statement

Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:

The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: This task is fashioned after the action of the Bash select statement.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Menu step by step in the Scala programming language

Source code in the scala programming language

import scala.util.Try

object Menu extends App {
  val choice = menu(list)

  def menu(menuList: Seq[String]): String = {
    if (menuList.isEmpty) "" else {
      val n = menuList.size

      def getChoice: Try[Int] = {
        println("\n   M E N U\n")
        menuList.zipWithIndex.map { case (text, index) => s"${index + 1}: $text" }.foreach(println(_))
        print(s"\nEnter your choice 1 - $n : ")
        Try {
          io.StdIn.readInt()
        }
      }

      menuList(Iterator.continually(getChoice)
        .dropWhile(p => p.isFailure || !(1 to n).contains(p.get))
        .next.get - 1)
    }
  }

  def list = Seq("fee fie", "huff and puff", "mirror mirror", "tick tock")

  println(s"\nYou chose : $choice")
}


  

You may also check:How to resolve the algorithm Xiaolin Wu's line algorithm step by step in the Haskell programming language
You may also check:How to resolve the algorithm Duffinian numbers step by step in the Quackery programming language
You may also check:How to resolve the algorithm Towers of Hanoi step by step in the Maple programming language
You may also check:How to resolve the algorithm Truncate a file step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm MAC vendor lookup step by step in the V (Vlang) programming language