gpt4 book ai didi

android - 如何将多个分隔符传递给子字符串(Kotlin/Android)?

转载 作者:行者123 更新时间:2023-12-02 12:40:03 28 4
gpt4 key购买 nike

我正在尝试制作一个计算器应用程序,并且我需要能够在有人第二次按下运算符(+,*,-,/)后获得最后一个值(第一个值保存没有问题,因为它是屏幕上唯一的数字)。
所以如果屏幕顶部有类似 (222 * 3333/12) 的东西,我需要得到 12。一旦我学会了如何做到这一点,我就可以弄清楚如何保存以前的数字/总和,然后在下一个数字(虽然我还没有制作那部分)。
我知道这是一种笨拙的做事方式,任何建议都值得赞赏。
因此,如果我使用 substringAfterLast() 并在其中插入一个运算符,我可以获取这个数字,但是,如果混合使用多个运算符(如 222 * 3333/12),我的 y 变量(见下文)只会显示“222 * 3333/12"而不是 12。
如何为子字符串使用多个分隔符?
顺便说一下,这是我的代码(请原谅我)

        multiplybutton.setOnClickListener {
var x = numbersEntered.toString()
var y = ""
//creates an array that holds the operators so it can be easily filtered out
val operators = arrayOf<Char>('*','/','+','-')
//prevents app from crashing by saving the last value before the operator is added, allowing us to create infinite number of operations
if (x.any(operators :: contains)){
// x.split(operators.toString())

y = x.substringAfterLast('*') // can't use my operator character array here? why? how do I iterate through it?
Toast.makeText(this, y.toString(), Toast.LENGTH_SHORT).show()

// previousvalue = y.toInt()
} else {
previousvalue = x.toInt()
}
numbersEntered.append("*")
numbersEnteredBox.setText(numbersEntered.toString())
isMultiply = true;
Toast.makeText(this, previousvalue.toString(), Toast.LENGTH_SHORT).show()
}
编辑:忽略斜体plz,不知道出了什么问题

最佳答案

对不起,也许我不完全理解你想要做什么,但你可以使用 split从这样的字符串中获取最后一个数字的函数222 * 3333 / 12 :

println("222 * 3333 / 12".split('+', '-', '*', '/').last().trim().toInt())
// prints 12

关于android - 如何将多个分隔符传递给子字符串(Kotlin/Android)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63643999/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com