Dae*_*ark 3 parseint kotlin android-studio
我使乐趣增加,项目数量减少。我想让 count.text 加上“T”字符。当我尝试编写这样的代码时。错误代码:java.lang.NumberFormatException:对于输入字符串:“1T”我该如何解决这个问题?有人可以帮忙吗??
fun increaseInteger() {
var count = findViewById<TextView>(R.id.integer_number)
count.text=intent.getStringExtra("case")+"T"
var countResult = parseInt(intent.getStringExtra("case")+"T")
var countValue = countResult+1
if (countValue >= 1 && !decrease.isEnabled) { decrease.isEnabled = true}
intent.putExtra("result",countValue)
display(countValue)
}
fun decreaseInteger() {
var count = findViewById<TextView>(R.id.integer_number)
count.text=intent.getStringExtra("case")+"T"
var countResult = parseInt(intent.getStringExtra("case")+"T")
var countValue = countResult-1
if (countValue <= 1) {decrease.isEnabled = false }
intent.putExtra("result",countValue)
display(countValue)
}
Run Code Online (Sandbox Code Playgroud)
API 非常简单:
"123".toInt() // returns 123 as Int
"123T".toInt() // throws NumberFormatException
"123".toIntOrNull() // returns 123 Int?
"123T".toIntOrNull() // returns null as Int?
Run Code Online (Sandbox Code Playgroud)
因此,如果您知道您的输入可能无法解析为 Int,您可以使用toIntOrNull
which 将在值无法解析时返回 null。它允许使用该语言提供的更多可空性工具,例如:
input.toIntOrNull() ?: throw IllegalArgumentException("$input is not a valid number")
Run Code Online (Sandbox Code Playgroud)
(此示例使用elvis运算符来处理 的不需要的空响应toIntOrNull
,替代方法将涉及 try/catch around toInt
)
归档时间: |
|
查看次数: |
1401 次 |
最近记录: |