Typechecking in Kotlin

You should check the text input when you perform click on your button, in perfect programm your code should look like this :

class MainActivity : AppCompatActivity() {
    lateinit var calculateButton: Button
    lateinit var editTextWeight: EditText
    lateinit var editTextHeight: EditText

    override fun onCreate(savedInstanceState: Bundle?) {

        editTextWeight = findViewById(R.id.weightEditText)
        editTextHeight = findViewById(R.id.heightEditText)
        calculateButton = findViewById(R.id.calcButton)

            val weight: Double = editTextWeight.text.toString().toDoubleOrNull() ?: 0.0
            val height: Double = editTextHeight.text.toString().toDoubleOrNull() ?: 0.0
            val bmi = weight / (height * height)

            if (bmi.isNaN())
                Toast.makeText([email protected],
                        "Input error, please try again!", Toast.LENGTH_LONG).show()
                Toast.makeText([email protected],
                        "Your BMI is $bmi", Toast.LENGTH_LONG).show()


CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top