我试图创建这样一个逻辑
if I Input "1-2+4" in Android TextView and after clicking a button
the output should Display as follows
1 - 2 = -1 // 1st line
-1 + 4 = 3 // 2nd line and so on...
without BODMAS Rule like,
first addition then minus etc., it should follow my input sequence我尝试了很多字符串函数,但找不到确切的logic...By使用字符串函数,我得到了类型错配等,这样的错误.我请求任何人抱着并引导我。谢谢
发布于 2022-09-27 20:23:01
这是你正在寻找的东西的快速迭代。Regex功能强大,但很危险,当它们被修改过最初的用法时,事情就开始崩溃了。
重点在这里。
operateBy方法中对整数做所有事情,这有助于Kotlin知道我们只处理整数,否则很难知道我们所期望的哪种类型,这是因为Int存在许多不同类型::减去Integer.parseInt方法中,它接受我们的字符串并使它们成为数字,所以我们实际上可以对它们进行数学运算,否则从字符串到Int的转换会导致意想不到的结果--cmd?.destructured?.run的空性来表示我们有一个成功的完全匹配。否则,我们会意识到我们已经到达了输入的末尾。
val input = "1-2+4+8-4/7*3"
val regex = Regex("""(-?\d+)([-+/*])(-?\d+)(.*)""")
parseInput(input)
println("Done!")
fun Int.operateBy(symbol: String, other: Int): Int = when(symbol) {
"-" -> minus(other)
"+" -> plus(other)
"/" -> div(other)
"*" -> times(other)
else -> other
}
fun parseInput(commands: String) {
if (commands.isEmpty()) return
val cmd = regex.find(commands)
cmd?.destructured?.run {
val first = component1()
val second = component2()
val third = component3()
val fourth = component4()
try {
val a = Integer.parseInt(first)
val b = Integer.parseInt(third)
val result = a.operateBy(second, b)
println("$a $second $b = $result")
parseInput("$result$fourth")
} catch (e: NumberFormatException) {
println("Error messaging")
}
}
}这将打印输出:
1 - 2 = -1
-1 + 4 = 3
3 + 8 = 11
11 - 4 = 7
7 / 7 = 1
1 * 3 = 3
Done!https://stackoverflow.com/questions/73871215
复制相似问题