Kotlin中的整数可以等于数学表达式吗? [英] Can an integer in Kotlin be equal to an math expression?

查看:68
本文介绍了Kotlin中的整数可以等于数学表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个解决数学表达式(例如2 + 2)的程序.我可以设置一个等于这样的整数吗?

I am making a program that solves a math expression, for example, 2+2. Can I set an integer equal to something like this:

val input = "2+2"
input.toInt()

推荐答案

Kotlin没有用于评估任意表达式的内置方法. toInt 函数只能解析一个String包含一个整数(它只是

Kotlin doesn't have any built in ways for evaluating arbitrary expressions. The toInt function can only parse a String containing a single whole number (it's just a wrapper for Integer.parseInt).

如果需要此功能,则必须自己解析和评估表达式.此问题与必须使用Java进行处理没什么不同,您可以在Java中找到讨论和多种解决方案(包括黑客,代码示例和库)

If you need this functionality, you'll have to parse and evaluate the expression yourself. This problem is no different than having to do it in Java, for which you can find discussion and multiple solutions (including hacks, code samples, and libraries) here.

这篇关于Kotlin中的整数可以等于数学表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆