Create a simple calculator consists of four operations addition, subtraction, multiplication and division using the Android system
code:
package show.a1s2.com.calproject;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView result;
private EditText a;
private EditText b;
private Button add;
private Button sub;
private Button mul;
private Button div;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
a = (EditText) findViewById(R.id.a);
b = (EditText) findViewById(R.id.b);
add = (Button) findViewById(R.id.add);
sub = (Button) findViewById(R.id.sub);
mul = (Button) findViewById(R.id.mul);
div = (Button) findViewById(R.id.div);
add.setOnClickListener(this);
sub.setOnClickListener(this);
mul.setOnClickListener(this);
div.setOnClickListener(this);
}
public void onClick(View v) {
float n1 = 0;
float n2 = 0;
float z = 0;
n1 = Float.parseFloat(a.getText().toString());
n2 = Float.parseFloat(b.getText().toString());
if (n1 < 0 || n2 < 0) {
result.setText("positive plz");
} else {
switch (v.getId()) {
case R.id.add:
z = n1 + n2;
break;
case R.id.sub:
z = n1 - n2;
break;
case R.id.mul:
z = n1 * n2;
break;
case R.id.div:
z = n1 / n2;
break;
}
result.setText("" + z);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Results:-