this is my code so far then it says to do this, and I can figure it out nActivit
ID: 3719384 • Letter: T
Question
this is my code so far then it says to do this, and I can figure it out
Explanation / Answer
// implements View.OnClickListener
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button addButton, subtractButton, multiplyButton, divideButton;
private EditText input1, input2;
private TextView answerText;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
addButton = (Button)findViewById(R.id.addButton);
subtractButton =(Button)findViewById(R.id.subtractButton);
multiplyButton =(Button)findViewById(R.id.multiplyButton);
divideButton = (Button) findViewById(R.id.divideButton);
// add this as listener for each button
addButton.setOnClickListener(this);
subtractButton.setOnClickListener(this);
multiplyButton.setOnClickListener(this);
divideButton.setOnClickListener(this);
input1 = (EditText)findViewById(R.id.input1);
input2 = (EditText)findViewById(R.id.input2);
answerText = (TextView) findViewById(R.id.answerText);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view)
{
Snackbar.make(view,"Replace with your own action",Snackbar.LENGTH_LONG).setAction("Action",null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if(id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// get the text from the input fields
double a = Double.parseDouble(input1.getText().toString());
double b = Double.parseDouble(input2.getText().toString());
if(v == addButton)
{
c = a+b; // calculate the sum
answerText.setText(c+""); // convert to string and set the text on the answerText TextView
}else if(v == subtractButton)
{
c = a-b; // calculate the difference
answerText.setText(c+""); // convert to string and set the text on the answerText TextView
}else if(v == multiplyButton)
{
c = a*b; // calculate multiplication
answerText.setText(c+""); // convert to string and set the text on the answerText TextView
}else if(v == divideButton)
{
if(b!= 0) // check divide by 0
{
c = a/b;
answerText.setText(c+""); // convert to string and set the text on the answerText TextView
}else{
answerText.setText("Infinity"); // convert to string and set the text on the answerText TextView
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.