如何用scala写一个计算机
时间: 2024-01-01 09:44:51 浏览: 72
作为AI语言模型,我可以为您提供一个scala计算器的示例代码,但是需要注意的是,这个计算器只是一个简单的示例,可能无法处理所有的输入和错误情况,也没有图形用户界面。
代码如下:
```scala
import scala.io.StdIn
object Calculator {
def main(args: Array[String]): Unit = {
println("Welcome to the Scala Calculator!")
while (true) {
val input = StdIn.readLine("Enter an equation (or exit to quit): ")
if (input == "exit") {
println("Thank you for using the Scala Calculator!")
System.exit(0)
}
try {
val result = Calculator.evaluate(input)
println(s"Result: $result")
} catch {
case e: Exception => println(s"Error: ${e.getMessage}")
}
}
}
def evaluate(input: String): Double = {
val tokens = input.split(" ")
if (tokens.length != 3) {
throw new IllegalArgumentException("Invalid input. Please enter an equation in the format: <number> <operator> <number>")
}
val leftOperand = tokens(0).toDouble
val rightOperand = tokens(2).toDouble
val operator = tokens(1)
operator match {
case "+" => leftOperand + rightOperand
case "-" => leftOperand - rightOperand
case "*" => leftOperand * rightOperand
case "/" => leftOperand / rightOperand
case _ => throw new IllegalArgumentException("Invalid operator. Please use one of the following: + - * /")
}
}
}
```
运行程序后,您可以输入一个算术表达式,例如:
```
Enter an equation (or exit to quit): 2 + 3
Result: 5.0
```
如果您输入的表达式无效,程序将抛出异常并显示错误消息:
```
Enter an equation (or exit to quit): 2 + 3 +
Error: Invalid input. Please enter an equation in the format: <number> <operator> <number>
```
阅读全文