java .lang.NumberFormatException: для входной строки: "16000 $" в kotlin - PullRequest
0 голосов
/ 22 января 2020

Я хочу, чтобы дисплей показывал «16000 $», прежде чем кликнуть «увеличить» или «уменьшить». когда я создаю код, подобный этой ошибке, вызванной: java .lang.NumberFormatException: для входной строки: "16000 $. но я должен отобразить $. Давайте проверим мой код и помогите мне, плз.


  var productprice = findViewById<TextView>(R.id.productPrice)
        productprice.text= intent.getStringExtra("price")+"$"
        var price = productPrice.text.toString().toInt()
        var inc_val= price
        var getPrice = price

        decrease.isEnabled=false

        increase.setOnClickListener {
            increaseInteger()
            getPrice+= inc_val
            productprice.text=getPrice.toString()+"$"
        }

        decrease.setOnClickListener {
            decreaseInteger()
            getPrice -= inc_val
            productprice.text=getPrice.toString()+"$"
        }

Ответы [ 2 ]

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

Вы пытаетесь разобрать строку с «$» в int, следовательно, вы получаете NumberFormatException.

Попробуйте вместо этого:

var productprice = findViewById<TextView>(R.id.productPrice)
        productprice.text= intent.getStringExtra("price")+"$"
        var price = parseInt(intent.getStringExtra("price"))
        var inc_val= price
        var getPrice = price

        decrease.isEnabled=false

        increase.setOnClickListener {
            increaseInteger()
            getPrice+= inc_val
            productprice.text=getPrice.toString()+"$"
        }

        decrease.setOnClickListener {
            decreaseInteger()
            getPrice -= inc_val
            productprice.text=getPrice.toString()+"$"
        }
0 голосов
/ 22 января 2020

var price = productPrice.text.toString().toInt() - вы пытаетесь конвертировать "16000 $" в Int здесь. Пожалуйста, сначала получите подстроку.

Формально правильный код:

val priceText = productPrice.text.toString()
val price = priceText.substring(0, priceText.length - 1).toInt()

Однако на самом деле я советую вам хранить значение внутри. Ваша цена является частью модели. Например, вы можете избежать разбора текста и просто прочитать значение из модели. Например, код будет выглядеть так:

var price = intent.getIntExtra("price") // we store int value here, not String
var inc_val= price
decrease.isEnabled=false
displayPrice()

increase.setOnClickListener {
    intent.setIntExtra(intent.getIntExtra("price") + inc_val) // read, update, save
    displayPrice()
}
decrease.setOnClickListener {
    intent.setIntExtra(intent.getIntExtra("price") - inc_val) // read, update, save
    displayPrice()
}


/*this function just shows price*/
fun displayPrice() {
   val price = intent.getIntExtra("price")

   productprice.text= "$price\$"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...