如何比较编辑文本与在 Kotlin 中转换为字符串的变量
How to compare Edit Text to Variable That was converted to String in Kotlin
I'm a beginner to Android Studio and I am building this simple game
我的问题是我试图获取编辑文本的值,然后将其转换为字符串。
而且我还将我的 int 变量转换为字符串以便比较
查看下面的代码
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()
}
}
问题是,如果我检查总和和文本是否相等,它总是错误的。而且我不知道该做什么了。
我认为这可能是因为空格。
使用 trim() 命令去除空格
所以
而不是 (sum == text) 使用 (sum == text.trim()).
还要确保firstnum + secondnum
这两个数字在计算前都已转换为整数。
Ps:正如@Tenfour04 所说,使用调试器可以帮助您缩小范围
I'm a beginner to Android Studio and I am building this simple game
我的问题是我试图获取编辑文本的值,然后将其转换为字符串。 而且我还将我的 int 变量转换为字符串以便比较
查看下面的代码
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()
}
}
问题是,如果我检查总和和文本是否相等,它总是错误的。而且我不知道该做什么了。
我认为这可能是因为空格。
使用 trim() 命令去除空格
所以
而不是 (sum == text) 使用 (sum == text.trim()).
还要确保firstnum + secondnum
这两个数字在计算前都已转换为整数。
Ps:正如@Tenfour04 所说,使用调试器可以帮助您缩小范围