SHARE
TWEET

Untitled

a guest Feb 27th, 2020 95 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.calculator;
  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.Toast;
  10.  
  11. public class MainActivity extends AppCompatActivity {
  12.  
  13.     EditText editText;
  14.     String lastOperation = "", operation = "";
  15.     Double number1, number2;
  16.  
  17.     @Override
  18.     protected void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         setContentView(R.layout.activity_main);
  21.         editText = findViewById(R.id.input_field);
  22.     }
  23.     public void onNumberClick(View view) {
  24.         if (!lastOperation.equals("")) {
  25.             number1 = Double.parseDouble(editText.getText().toString());
  26.             editText.setText("");
  27.             operation = lastOperation;
  28.             lastOperation = "";
  29.         }
  30.         Button button = (Button) view;
  31.         editText.append(button.getText().toString());
  32.     }
  33.     public void onOperationClick(View view) {
  34.         Button button = (Button)view;
  35.         lastOperation = button.getText().toString();
  36.         if (lastOperation.equals("=")) {
  37.             number2 = Double.parseDouble(editText.getText().toString());
  38.             onResultClick(number1, number2, operation);
  39.         }
  40.         if (lastOperation.equals("AC")) {
  41.             editText.setText("");
  42.             number1 = 0d;
  43.             number2 = 0d;
  44.             lastOperation = "";
  45.             operation = "";
  46.         }
  47.     }
  48.     public void onResultClick (Double number1, Double number2, String operation) {
  49.         Double result = 0d;
  50.         switch (operation) {
  51.             case "+":
  52.                 result = number1 + number2;
  53.                 break;
  54.             case "-":
  55.                 result = number1 - number2;
  56.                 break;
  57.             case "x":
  58.                 result = number1 * number2;
  59.                 break;
  60.             case "/":
  61.                 result = number1 / number2;
  62.                 break;
  63.             case "%":
  64.                 result = number1 % number2;
  65.                 break;
  66.         }
  67.         editText.setText(Double.toString(result));
  68.     }
  69. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top