4

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


  • Well the error message indicates what the problem is: you add the char "T" to a number and try to parse that to an int. You should parse the count to an it first, increment it and AFTERWARDS add the char T. – Aaron Jan 27 '20 at 07:20
  • thanks for u r comment, I already try it many times . but i dont know how to solve it . –  Jan 27 '20 at 07:23
  • Why do you add T in the first place to your int? Try removing the T and your code should be good to go :) – Aaron Jan 27 '20 at 07:29
  • What is the actual input and how does the desired output look like? – deHaar Jan 27 '20 at 07:30
  • Does this answer your question? [How to convert String to Int in Kotlin?](https://stackoverflow.com/questions/50570262/how-to-convert-string-to-int-in-kotlin) – Willi Mentzel Jan 27 '20 at 08:10
  • I need add 'T' .. it is duty. coz of project work –  Jan 27 '20 at 08:24

2 Answers2

12

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)

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
2

You can use these

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?
kishan verma
  • 984
  • 15
  • 17