你好,我正在做一个随机数字猜测游戏。问题是,如果用户没有输入任何数字,并按下按钮,如果条件的answerEmpty变量应执行,并在结果文本中显示“请输入一个数字”。但程序崩溃时,我按下按钮。else if和else条件工作,但启动if条件不工作。请帮助
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Calling button method
val button = findViewById<Button>(R.id.guessBtn)
//Set on click listener for the button
button.setOnClickListener {
buttonPressed()
}
}
private fun buttonPressed() {
//Method to find view from activity_main
val result = findViewById<TextView>(R.id.result)
val userAnsEditText = findViewById<EditText>(R.id.answer)
val userAnsText = userAnsEditText.text.toString()
val userAnsInt = userAnsText.toInt()
//This variable will display the answer
val answerCorrect = "Congrats, you have correctly guessed the number"
val answerWrong = "Sorry,you have guessed the wrong number"
val answerEmpty = "Please enter a number"
//Making random numbers from 1 to 10
val randomValues = Random.nextInt(1, 11)
//Adding a condition to check if user answer matches the random answer
if(userAnsInt == null){
result.text = answerEmpty
}
else if(userAnsInt == randomValues){
result.text = answerCorrect
}
else{
result.text = answerWrong
}
}
字符串
2条答案
按热度按时间1cklez4t1#
在
int
中解析之前,应检查EditText
文本是否为空或非条件添加以下条件
字符串
val userAnsInt = userAnsText.toInt()
线之前。它会修复你的崩溃。
添加
isEmpty()
条件后,buttonPressed()
函数如下所示。型
kpbwa7wx2#
例如,使用Try catch块
字符串
“下面是各部分的细目:
**try:**可能引发异常的代码放在此块中。**catch:**如果try块中出现异常,则执行catch块。它指定要捕获的异常类型和处理它的代码。**finally:**此块包含无论是否出现异常都会执行的代码。它是可选的。之后您的应用不会崩溃。它会显示错误,您可以在吐司或输出窗口中打印错误。