2. As you probably have noticed, the code is absolutely
the same in each onClickListener except of the
sign operation between two variables.
The additional challenge in programming is to
decrease complexity and length of the code, and to
make as readable and concise as possible.
Mostly its done by swapping repeatable code with
functions, reusable piece of code.
3. The following function <calculate>, will:
1. Takes input <sign> (with type String).
2.Takes both calculator's input variables.
3. Through <if statements> defines the sign variable and
calculates result appropriately
4. Prints off result in <answer> TextField
private void calculate(String sign) {
firstVar = Integer.parseInt(firstInput.getText().toString());
secondVar = Integer.parseInt(secondInput.getText().toString());
if (sign == "+") result = firstVar + secondVar;
else if (sign == "-") result = firstVar - secondVar;
else if (sign == "/") result = firstVar / secondVar;
else if (sign == "*") result = firstVar * secondVar;
answer.setText(String.valueOf(result));
}
4. Now we can remove
previous code inside
onClick method with
function
calculate(<math sign
relatively to the button>)
plus.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
calculate("+");
}
});
minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
calculate("-");
}
});
mult.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
calculate("*");
}
});
div.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
calculate("/");
}
});
5. Program is shorter but result is the
same.
Thats what we aim for other apps you
are going to make as well.
Now try to fix bug when you make
calculation without assigning
variables yourself.
(hint: use if statements to illuminate null value of the variables)
6. Program is shorter but result is the
same.
Thats what we aim for other apps you
are going to make as well.
Now try to fix bug when you make
calculation without assigning
variables yourself.
(hint: use if statements to illuminate null value of the variables)