Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.mybmicalculator16092022;
- import androidx.appcompat.app.AppCompatActivity;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.LinearLayout;
- import android.widget.RadioGroup;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends AppCompatActivity {
- // 1 - define variables
- private EditText etNumber1;
- private EditText etNumber2;
- private TextView tvResult;
- private RadioGroup rgOperation;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // 0 - select a layout file for the activity
- setContentView(R.layout.activity_main);
- // 2 - bind each variable to a view from the layout
- etNumber1 = findViewById(R.id.etNo1);
- etNumber2 = findViewById(R.id.etNo2);
- tvResult = findViewById(R.id.tvResult);
- rgOperation = findViewById(R.id.rgOperation);
- }
- public void btnClicked(View view) {
- int n1, n2;
- // check user input data
- try {
- n1 = Integer.parseInt(etNumber1.getText().toString());
- } catch (Exception e) {
- tvResult.setText("Error: First number is missing or not integer");
- return;
- }
- try {
- String t = etNumber2.getText().toString();
- n2 = Integer.parseInt(t);
- } catch (Exception e) {
- tvResult.setText("Error: Second number is missing or not integer");
- return;
- }
- // check for selected operation
- double res = 0;
- String sign = "";
- int id = rgOperation.getCheckedRadioButtonId();
- // id=-1 if no operation was selected
- if (id == R.id.rbAdd) {
- res = n1 + n2;
- sign = "+";
- } else {
- if (id == R.id.rbSub) {
- res = n1 - n2;
- sign = "-";
- } else {
- if (id == R.id.rbMul) {
- res = n1 * n2;
- sign = "*";
- } else {
- if (id == R.id.rbDiv) {
- res = (double) n1 / n2;
- sign = "/";
- // error - res =(double) (n1 / n2);
- } else {
- tvResult.setText("You should Select an operation first");
- }
- }
- }
- }
- // display result if no errors were found
- if (sign != "") {
- tvResult.setText(n1 + sign + n2 + " = " + res);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement