我是 Android Studio 的初學者,我正在構建這個簡單的游戲
我的問題是我試圖獲取編輯文本的值,然后將其轉換為字串。而且我還將我的 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()
}
}
問題是,如果我檢查總和和文本是否相等,它總是錯誤的。我不知道該做什么了。
uj5u.com熱心網友回復:
我認為這可能是因為空格。
使用 trim() 命令去除空格
所以
而不是 (sum == text) 使用 (sum == text.trim())。
還要確保firstnum secondnum在計算之前這兩個數字都已轉換為整數。
Ps:正如@Tenfour04 所說,使用除錯器可以幫助您縮小范圍 在 Android Studio 中使用除錯器
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449992.html
