Here you can learn how to perform simple Airthmatic operations in Android. This is applicable for only integer data type.
Coding is below -
package com.example.username.SimpleCalculatorforInt;
}
// Similarly we perform same coding for rest of operations ( subtraction , multiplication, division)
public void onSubClick(View view) { EditText e1 = (EditText)findViewById(R.id.editText); EditText e2 = (EditText)findViewById(R.id.editText2); TextView res = (TextView)findViewById(R.id.textView4); int num1 = Integer.parseInt(e1.getText().toString()); int num2 = Integer.parseInt(e2.getText().toString()); int sub = num1 - num2; res.setText(Integer.toString(sub)); } public void onMultClick(View view) { EditText e1 = (EditText)findViewById(R.id.editText); EditText e2 = (EditText)findViewById(R.id.editText2); TextView res = (TextView)findViewById(R.id.textView4); int num1 = Integer.parseInt(e1.getText().toString()); int num2 = Integer.parseInt(e2.getText().toString()); int mult = num1 * num2; res.setText(Integer.toString(mult)); } public void onDivClick(View view) { EditText e1 = (EditText)findViewById(R.id.editText); EditText e2 = (EditText)findViewById(R.id.editText2); TextView res = (TextView)findViewById(R.id.textView4); int num1 = Integer.parseInt(e1.getText().toString()); int num2 = Integer.parseInt(e2.getText().toString()); int div = num1 / num2; res.setText(Integer.toString(div)); } }
Explanation of Code -
1. Variable declaration - EditText e1, EditText e2, TextView res
2. Variable Casting - EditText e1 =(EditText)findViewById(R.id.editText);
(same for other variables)
User entered number values in edit text widgets which
are in integer format and are converted into string format
and stored into num1 and num2. and for that we need to
use code e1.getText().toString()and e2.getText().toString()
Now we need to perform add operation so numbers which
are stored into num1 and num2 are in string format are again
converted into integer format by using code Integer.parseInt
No comments:
Post a Comment