您好,我是 android 軟體開發的初學者。我正在制作一個計算器應用程式來測驗我的技能。在計算器中,有 0-9 個數字和其他一些運算子,如 、-、*、/ 等。在使用 Equal 功能時,我必須確保 TextView 的最后一個字串具有任何數字 (0-9) , 不是任何運算子。
我同樣的樂趣是這樣的:
fun onEqual(view: View) {
if (tv_input.text.contains("0-9")) {
Toast.makeText(this, "Last string is a number, not operator", Toast.LENGTH_SHORT).show()
}
}
uj5u.com熱心網友回復:
您需要使用 Kotlin 正則運算式匹配
val lastString = "573" // input
val pattern = "-?\\d (\\.\\d )?".toRegex()
/**
-? allows zero or more - for negative numbers in the string.
\\d checks the string must have at least 1 or more numbers (\\d).
(\\.\\d )? allows zero or more of the given pattern (\\.\\d )
In which \\. checks if the string contains . (decimal points) or not
If yes, it should be followed by at least one or more number \\d .
**/
val isLastString = pattern.matches(lastString)
uj5u.com熱心網友回復:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/ends-with.html
fun String.endsWith(
suffix: String,
ignoreCase: Boolean = false
): Boolean
如果此字串以指定的后綴結尾,則回傳 true。
uj5u.com熱心網友回復:
感謝大家。我做了我自己的解決方案。
這是我寫的代碼:
fun onEqual(view: View) {
if (!tv_input.text.toString().equals("")) {
val last = tv_input.text.toString()
val lastNumber: String = last.get(last.length - 1).toString()
Toast.makeText(this, lastNumber, Toast.LENGTH_SHORT).show()
}else {
return
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400115.html
上一篇:再次運行程式后如何將數字重置為0
