Basically, this is the second activity code. My app is a math game where it gives you random numbers and depending on the gamemode you are playing, it will either ask you to add or subtrtact or multiply or divide the numbers. The home screen is 4 buttons and each button says one of addition subtraction multiplication and division. The error i got was when i clicked on the addition button, it crashed. To debug I tried commenting out the while loop and it worked. So i know my problem is in the while loop i just do not know where inside the while loop i am finding and error. Thats why I pasted the second activity of my code so maybe someone can review it and find the error. Thanks!
package com.sohum.thebasicmathgame
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random
class AddScreen : AppCompatActivity() {
lateinit var checkButton: Button
lateinit var answerEditText: EditText
lateinit var questionTextView: TextView
lateinit var scoreTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_screen)
var correct:Boolean = true
var theScore:Int = 0
while (correct) {
var num1:Int = rand(1,10)
var num2:Int = rand(1,10)
var answer:Int = num1+num2
questionTextView.setText("$num1 + $num2 = ")
scoreTextView.text = theScore.toString()
checkButton.setOnClickListener{
var check:String = answerEditText.text.toString()
if (check == answer.toString()){
Toast.makeText(this@AddScreen,"Correct Answer!", Toast.LENGTH_SHORT)
++theScore
}
else {
correct = false
showIncorrect()
}
}
}
}
private fun rand(start: Int, end: Int): Int {
require(start <= end) { "Illegal Argument" }
return Random(System.nanoTime()).nextInt(start, end + 1)
}
fun showIncorrect()
{
var showIncorrectDialog = AlertDialog.Builder(this@AddScreen)
showIncorrectDialog.setTitle("Incorrect!").setMessage("You got the answer incorrect! Sorry! Your Score was ${scoreTextView.text}").setIcon(R.drawable.wrong).setCancelable(false).setPositiveButton("Go To Home Screen",
DialogInterface.OnClickListener { dialogInterface, which ->
var homeScreen = Intent(this@AddScreen, MainActivity::class.java)
startActivity(homeScreen)
})
showIncorrectDialog.create().show()
}
}