Search code examples
android-studiokotlinparseint

How to use parseInt in kotlin?


I making fun increase, decrease for item count. I want make count.text plus "T" Character. when I tried to make code like this. error code: java.lang.NumberFormatException: For input string: "1T" How can I solve this problem? Any one can help??

   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)
    }



Solution

  • The API is pretty straightforward:

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

    So if you know your input might not be parseable to an Int, you can use toIntOrNull which will return null if the value was not parseable. It allows to use further nullability tools the language offers, e.g.:

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

    (This example uses the elvis operator to handle the undesired null response of toIntOrNull, the alternative would involve a try/catch around toInt)