【问题标题】:Scala calculator that accepts three string parameters接受三个字符串参数的 Scala 计算器
【发布时间】:2019-04-21 12:54:45
【问题描述】:

如何编写一个接受三个字符串参数的叫做calculator的方法:

def calculator(operand1: String, operator: String, operand2: String): Unit

将操作数转换为 Int; 对两个操作数执行所需的数学运算符(+、-、* 或 /) 打印结果或一般错误消息

【问题讨论】:

  • 欢迎来到 StackOverflow。这个网站奖励努力。你都尝试了些什么?向我们展示不起作用的代码,以便我们更好地了解您对 Scala 语言的理解。

标签: scala functional-programming


【解决方案1】:

您的问题表明您几乎没有为自己寻找解决方案付出任何努力。

下次在 StackOverflow 上提问时,请询问有关现有代码的问题(例如,“为什么我会收到此异常?”或“为什么我的代码无法编译?”)并且不要假设一些互联网代码猴子会神奇地编写你的代码。


无论如何,您似乎是 SO 的新成员,def calculator 看起来像这样:

import scala.collection.immutable.StringOps._
import scala.util.{Try, Success, Failure}

def calculator(left: String, op: String, right: String): Unit = {

  def parse(value: String) = Try(value.toDouble)

  (parse(left), parse(right)) match {
    case (Success(leftDouble), Success(rightDouble)) => {
      op match {
        case "/" => println(leftDouble / rightDouble)
        case "*" => println(leftDouble * rightDouble)
        case "+" => println(leftDouble + rightDouble)
        case "-" => println(leftDouble - rightDouble)
        case invalid: String => println(s"Invalid operator $invalid.")
      }
    }
    case (Failure(e), _) => println(s"Could not parse $left.")
    case(_, Failure(e)) => println(s"Could not parse $right.")
    case(Failure(e1), Failure(e2)) => println(s"Could not parse $left and $right.")
  }

}

Try it out!

如果您需要任何解释,请随时发表评论。

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多