Home > Back-end >  How to compare Edit Text to Variable That was converted to String in Kotlin
How to compare Edit Text to Variable That was converted to String in Kotlin

Time:03-26

I'm a beginner to Android Studio and I am building this simple game

My problem is that I tried to get the Value of the Edit Text and then converted it to string. And I also converted my int variable to string in order to compare

see code below

fun entEvent(view: View){
    val sum = (firstnum   secondnum).toString()
    val text = editText2.text.toString()
    if (sum == text){
        val alert = AlertDialog.Builder(this)
        //Title for alert dialog
        alert.setTitle("Mental Math")

        //set message for alert dialog
        alert.setMessage(R.string.diaMessage)

        //performing positive action
        alert.setPositiveButton("Ok"){
                dialogInterface, which ->
            Toast.makeText(applicationContext,"Congrats, You are A math genius", Toast.LENGTH_SHORT).show()
        }
        val alertDialog: AlertDialog = alert.create()
        alertDialog.setCancelable(false)
        alertDialog.show()
    }
    if (sum!=text){

        val alert = AlertDialog.Builder(this)
        //Title for alert dialog
        alert.setTitle("Mental Math")

        //set message for alert dialog
        alert.setMessage(R.string.diaMessage2)

        //performing positive action
        alert.setPositiveButton("Ok"){
                dialogInterface, which ->
            Toast.makeText(applicationContext,"Sorry, Try Again", Toast.LENGTH_SHORT).show()
        }
        val alertDialog: AlertDialog = alert.create()
        alertDialog.setCancelable(false)
        alertDialog.show()
    }

}

The problem is that if I check if the sum and text is equals it is always false. And I dont know what do anymore.

CodePudding user response:

I think this is probably because of whitespace.

Use the trim() command to get rid of whitespace

so

instead of (sum == text) use (sum == text.trim()).

ALso make sure that firstnum secondnum both these nos have been converted to an Integer before calculation.

Ps: As @Tenfour04 said using the debugger would help you narrow it down Using Debugger in Android Studio

  • Related