- package com.example.mathchallenge;
- import androidx.appcompat.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import java.util.Random;
- public class MainActivity extends AppCompatActivity {
- int score = 0; //to keep track of the user's score
- int num1, num2, answer; //variables to hold the first number, second number, and answer respectively
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity\_main);
- newProblem(); //generate a new problem when the app starts
- }
- public void checkAnswer(View view) {
- EditText editText = findViewById(R.id.answer);
- int userAnswer;
- try {
- userAnswer = Integer.parseInt(editText.getText().toString());
- } catch (NumberFormatException e) {
- editText.setError("Invalid answer!");
- return;
- }
- if (userAnswer == answer) {
- score++;
- TextView textView = findViewById(R.id.score);
- textView.setText("Score: " + score);
- TextView message = findViewById(R.id.message);
- message.setText("Correct!");
- } else {
- TextView message = findViewById(R.id.message);
- message.setText("Sorry, the correct answer was " + answer + ".");
- }
- }
- public void playAgain(View view) {
- newProblem();
- score = 0;
- TextView textView = findViewById(R.id.score);
- textView.setText("Score: 0");
- }
- private void newProblem() {
- Random random = new Random();
- int operator = random.nextInt(4); //generating a number to determine the operator
- switch (operator) {
- case 0: //addition
- num1 = random.nextInt(51); //generate a random number between 0 and 50
- num2 = random.nextInt(51); //generate another random number between 0 and 50
- answer = num1 + num2;
- break;
- case 1: //subtraction
- num1 = random.nextInt(101);
- num2 = random.nextInt(num1+1); //generate a number between 0 and num1
- answer = num1 - num2;
- break;
- case 2: //multiplication
- num1 = random.nextInt(13); //generate a random number between 0 and 12
- num2 = random.nextInt(13);
- answer = num1*num2;
- break;
- case 3: //division
- num1 = random.nextInt(13) * random.nextInt(13); //multiply two random numbers between 0 and 12 to get num1
- num2 = random.nextInt(12) + 1; //generate a random number between 1 and 12 for num2
- answer = num1 / num2;
- break;
- }
- TextView textView = findViewById(R.id.problem);
- textView.setText(num1 + " ? " + num2 + " = ?");
- TextView message = findViewById(R.id.message);
- message.setText("");
- EditText editText = findViewById(R.id.answer);
- editText.setText("");
- }
- }