Как использовать parseInt в kotlin? - PullRequest
1 голос
/ 27 января 2020

Я высмеиваю увеличение, уменьшение количества предметов. Я хочу сделать 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)
    }


Ответы [ 2 ]

7 голосов
/ 27 января 2020

API довольно прост:

"123".toInt() // returns 123 as Int
"123T".toInt() // throws NumberFormatException
"123".toIntOrNull() // returns 123 Int?
"123T".toIntOrNull() // returns null as Int?

Так что, если вы знаете, что ваш ввод может быть не разбирается в Int, вы можете использовать toIntOrNull, который будет возвращать ноль, если значение не было проанализировано. Это позволяет использовать другие инструменты обнуляемости, предлагаемые языком, например:

input.toIntOrNull() ?: throw IllegalArgumentException("$input is not a valid number")

(В этом примере оператор elvis используется для обработки нежелательного нулевого ответа toIntOrNull, альтернатива может включать попытка / ловить вокруг toInt)

2 голосов
/ 27 января 2020

Вы можете использовать эти

val str = "12345"
val str_new = "12345B"
str.toInt() // returns 123 as Int
str_new.toInt() // throws NumberFormatException
str.toIntOrNull() // returns 123 Int?
str_new.toIntOrNull() // returns null as Int?
...