Hello so I’m making a random number guesser game. The problem is if a user doesn’t input any number and presses the button in the if condition the answerEmpty variable should be executed and the "Please enter a number" should be shown in the result text. But the program crashes when I press the button. The else if and else condition works but the starting if condition doesnt work. Please help
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
}
}
>Solution :
You should check EditText text is empty or not condition before parse to in int
Add below condition
if (userAnsText.isEmpty()) {
result.text = answerEmpty
}
before val userAnsInt = userAnsText.toInt() line.
It will fix your crash.
Your buttonPressed() function looks below after adding isEmpty() condition.
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 answerCorrect = "Congrats, you have correctly guessed the number"
val answerWrong = "Sorry,you have guessed the wrong number"
val answerEmpty = "Please enter a number"
if (userAnsText.isEmpty()) {
result.text = answerEmpty
} else {
val userAnsInt = userAnsText.toInt()
//This variable will display the answer
//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
//when condition more relavant in kotlin than if-else if-else
when (userAnsInt) {
null -> result.text = answerEmpty
randomValues -> result.text = answerCorrect
else -> result.text = answerWrong
}
}
}