java.lang.NumberFormatException: Invalid int: “” : Error

前端 未结 5 1987
南笙
南笙 2021-01-21 08:22

I am doing some calculation but unable to parse a string into int or even in float.I searched for solution and i read it somewhere there must be a empty string but i checked my

5条回答
  •  星月不相逢
    2021-01-21 09:06

    you should get the values inside a method so that your app does not try to assign the values immediatly you are creating them check below how am doing it using kotlin

         myresult = findViewById(R.id.txtresult)
         val1 = findViewById(R.id.valone)
         val2 = findViewById(R.id.valtwo)
    

    after getting the field use method as below

        fun calculate() : Int {
    
            var value1 = Integer.parseInt(val1.text.toString())
            var value2 = val2.text.toString().toInt()
            var result : Int
    
            when (opType){
    
                "+" ->{result = value1 + value2
                        return result
                     }
                "-" ->{result = value1 - value2
                    return result
                }
                "*" -> {result = value1 * value2
                    return result
                }
                "/" -> {result = value1 / value2
                    return result
                } else -> result = 20
    
            }
    
            return result
        }
    
         btn.setOnClickListener{
    
            println(calculate().toString())
            myresult.text = calculate().toString()
    
    
        }
    

    for those moving to kotlin and finding the same error I hope this code will help you

提交回复
热议问题