Advertisement
mmayoub

MyMath, Java file

Oct 7th, 2022
993
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | Software | 0 0
  1. package com.example.mymath;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4.  
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.TextView;
  10. import android.widget.Toast;
  11.  
  12. import java.util.Random;
  13.  
  14. public class MainActivity extends AppCompatActivity {
  15.     private Random rnd;
  16.     private TextView tvExercise;
  17.     private EditText etAnswer;
  18.     private Button btnCheck;
  19.     private int answer;
  20.  
  21.     @Override
  22.     protected void onCreate(Bundle savedInstanceState) {
  23.         super.onCreate(savedInstanceState);
  24.         setContentView(R.layout.activity_main);
  25.  
  26.         tvExercise = findViewById(R.id.tvExercise);
  27.         etAnswer = findViewById(R.id.etAnswer);
  28.         btnCheck = findViewById(R.id.btnCheck);
  29.  
  30.         rnd = new Random();
  31.  
  32.         showExercise();
  33.     }
  34.  
  35.     public void showExercise() {
  36.         int n1, n2;
  37.         int op;
  38.         String operation = "";
  39.         n1 = rnd.nextInt(11);
  40.         n2 = rnd.nextInt(11);
  41.  
  42.         op = rnd.nextInt(4);
  43.         if (op == 0) {
  44.             // +
  45.             operation = " + ";
  46.             answer = n1 + n2;
  47.         } else if (op == 1) {
  48.             // -
  49.             operation = " - ";
  50.             answer = n1 - n2;
  51.         } else if (op == 2) {
  52.             // *
  53.             operation = " * ";
  54.             answer = n1 * n2;
  55.         } else if (op == 3) {
  56.             // /
  57.             operation = " / ";
  58.             answer = n1 / n2;
  59.         }
  60.  
  61.         tvExercise.setText(n1 + operation + n2);
  62.         etAnswer.setText("");
  63.     }
  64.  
  65.  
  66.     public void checkAnswer(View view) {
  67.         int userAnswer;
  68.  
  69.         userAnswer = Integer.parseInt(etAnswer.getText().toString());
  70.  
  71.         if (userAnswer == answer) {
  72.             // right answer
  73.             Toast.makeText(this, "good work! It's the right answer", Toast.LENGTH_LONG).show();
  74.             showExercise();
  75.         } else {
  76.             // wrong answer
  77.             Toast.makeText(this, "OOOh . . .try again", Toast.LENGTH_LONG).show();
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement