Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.08 KB | None | 0 0
  1. object GeometricShapes extends App {
  2.  
  3.   val inputHeight = scala.io.StdIn.readLine("Please insert the height of your shape:")
  4.   val validHeight = validInput(inputHeight)
  5.   println(s" höhe: $validHeight")
  6.  
  7.   val inputWidth = scala.io.StdIn.readLine("Please insert the width of your shape:")
  8.   val validWidth = validInput(inputWidth)
  9.   println(s" höhe: $validWidth")
  10.  
  11.   val shape = scala.io.StdIn.readLine("Enter the type of your shape (rectangle,triangle or circle):")
  12.   val shape1 = shape.trim()
  13.   shapes(validHeight , validWidth, shape1)
  14.  
  15.  
  16.  
  17.   def validInput(input: String): Double = {
  18.     val pattern = """\s*(\d+[.,]?\d*)\s*(mm|cm|dm|m)\s*""".r
  19.  
  20.     input match {
  21.       case pattern(value, unit) => {
  22.         val replacedValue = value.replace(",", ".")
  23.         if (unit == "mm") return replacedValue.toDouble / 10.0
  24.         else if (unit == "dm") return replacedValue.toDouble * 10
  25.         else if (unit == "m")  return replacedValue.toDouble * 100.0
  26.         else return replacedValue.toDouble
  27.  
  28.       }
  29.       case _ => {
  30.         println("This is not a valid dimension! Use a number followed by either \"m\",\"dm\",\"cm\" or \"mm\".")
  31.         System.exit(0)
  32.         return 0.0}
  33.     }
  34.   }
  35.  
  36.   def shapes(height: Double, width: Double, shape: String): Any = {
  37.    
  38.     shape match {
  39.       case  "rectangle" => println("The area of your rectangle with height= %.2fcm and width=%.2fcm is: %.2f cm2".format(height, width, width*height))
  40.       case "triangle" => println("The area of your triangle with height= %.2fcm and width=%.2fcm is: %.2f cm2".format(height, width, ((width*height)/2).toDouble))
  41.       case "circle" => {
  42.         if(height == width) println("The area of your circle with height= %.2fcm and width=%.2fcm is: %.2f cm2".format(height, width, height*height*math.Pi))
  43.         else {
  44.           println("Height and width of a circle need to be equal!")
  45.           System.exit(0)
  46.         }
  47.       }
  48.       case wrong => println("Shape \"%s\" is not supported. Please use \"rectangle\",\"triangle\" or \"circle\"".format(shape))
  49.     }
  50.    
  51.    
  52.    
  53.   }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement