Advertisement
Apauldin

MainActivity

Sep 11th, 2021 (edited)
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. package com.example.calcapp2;
  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.  
  11. public class MainActivity extends AppCompatActivity {
  12.     public EditText p1, p2;
  13.     public Button b_add, b_minus, b_mul, b_del;
  14.     public TextView textView;
  15.     int a, b;
  16.  
  17.     @Override
  18.     protected void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         setContentView(R.layout.activity_main);
  21.         p1 = findViewById(R.id.arg1);
  22.         p2 = findViewById(R.id.arg2);
  23.         b_add = findViewById(R.id.add);
  24.         b_minus = findViewById(R.id.subtr);
  25.         b_mul = findViewById(R.id.mul);
  26.         b_del = findViewById(R.id.divide);
  27.         textView = findViewById(R.id.answer);
  28.     }
  29.  
  30.     public boolean init() {
  31.         boolean ans = true;
  32.         try {
  33.             a = Integer.parseInt(p1.getText().toString());
  34.         } catch (NumberFormatException e) {
  35.             ans = false;
  36.         }
  37.         try {
  38.             b = Integer.parseInt(p2.getText().toString());
  39.         } catch (NumberFormatException r) {
  40.             ans = false;
  41.         }
  42.         if (!ans) {
  43.             textView.setText("Input Error");
  44.         }
  45.         return ans;
  46.     }
  47.  
  48.     public void onClickAdd(View view) {
  49.         boolean f = init();
  50.         if (f) {
  51.             textView.setText(Integer.toString((a + b)));
  52.         }
  53.     }
  54.  
  55.     public void onClickMinus(View view) {
  56.         boolean f = init();
  57.         if (f) {
  58.             textView.setText(Integer.toString((a - b)));
  59.         }
  60.     }
  61.  
  62.     public void onClickMul(View view) {
  63.         boolean f = init();
  64.         if (f) {
  65.             textView.setText(Integer.toString((a * b)));
  66.         }
  67.     }
  68.  
  69.     public void onClickDel(View view) {
  70.         boolean f = init();
  71.         if (f) {
  72.             if (b != 0) {
  73.                 textView.setText(Integer.toString((a / b)));
  74.             } else {
  75.                 textView.setText("Div by zero");
  76.             }
  77.         }
  78.     }
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement